convert 12-hour hh:mm AM/PM to 24-hour hh:mm - javascript

Is there any simple way to convert 12-hour hh:mm AM/PM to 24-hour hh:mm using jquery?
Note: not using any other libraries.
I have a var time = $("#starttime").val() that returns a hh:mm AM/PM.

Try this
var time = $("#starttime").val();
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);

This question needs a newer answer :)
const convertTime12to24 = (time12h) => {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (hours === '12') {
hours = '00';
}
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return `${hours}:${minutes}`;
}
console.log(convertTime12to24('01:02 PM'));
console.log(convertTime12to24('05:06 PM'));
console.log(convertTime12to24('12:00 PM'));
console.log(convertTime12to24('12:00 AM'));

This will help :
function getTwentyFourHourTime(amPmString) {
var d = new Date("1/1/2013 " + amPmString);
return d.getHours() + ':' + d.getMinutes();
}
Example :
getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"
Update :
Note : There should be a space for timestring between "Time" and "am/pm".

I had to do something similar but I was generating a Date object so I ended up making a function like this:
function convertTo24Hour(time) {
var hours = parseInt(time.substr(0, 2));
if(time.indexOf('am') != -1 && hours == 12) {
time = time.replace('12', '0');
}
if(time.indexOf('pm') != -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
return time.replace(/(am|pm)/, '');
}
I think this reads a little easier. You feed a string in the format h:mm am/pm.
var time = convertTo24Hour($("#starttime").val().toLowerCase());
var date = new Date($("#startday").val() + ' ' + time);
Examples:
$("#startday").val('7/10/2013');
$("#starttime").val('12:00am');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 00:00:00 GMT-0700 (PDT)
$("#starttime").val('12:00pm');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 12:00:00 GMT-0700 (PDT)
$("#starttime").val('1:00am');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 01:00:00 GMT-0700 (PDT)
$("#starttime").val('12:12am');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 00:12:00 GMT-0700 (PDT)
$("#starttime").val('3:12am');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 03:12:00 GMT-0700 (PDT)
$("#starttime").val('9:12pm');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 21:12:00 GMT-0700 (PDT)

Here my solution including seconds:
function convert_to_24h(time_str) {
// Convert a string like 10:05:23 PM to 24h format, returns like [22,5,23]
var time = time_str.match(/(\d+):(\d+):(\d+) (\w)/);
var hours = Number(time[1]);
var minutes = Number(time[2]);
var seconds = Number(time[3]);
var meridian = time[4].toLowerCase();
if (meridian == 'p' && hours < 12) {
hours += 12;
}
else if (meridian == 'a' && hours == 12) {
hours -= 12;
}
return [hours, minutes, seconds];
};

function timeConversion(s) {
var time = s.toLowerCase().split(':');
var hours = parseInt(time[0]);
var _ampm = time[2];
if (_ampm.indexOf('am') != -1 && hours == 12) {
time[0] = '00';
}
if (_ampm.indexOf('pm') != -1 && hours < 12) {
time[0] = hours + 12;
}
return time.join(':').replace(/(am|pm)/, '');
}
Call the function with string params:
timeConversion('17:05:45AM')
or
timeConversion('07:05:45PM')

i must recommend a library: Moment
code:
var target12 = '2016-12-08 9:32:45 PM';
console.log(moment(target12, 'YYYY-MM-DD h:m:s A').format('YYYY-MM-DD HH:mm:ss'));

For anybody reading this in the future, here is a simpler answer:
var s = "11:41:02PM";
var time = s.match(/\d{2}/g);
if (time[0] === "12") time[0] = "00";
if (s.indexOf("PM") > -1) time[0] = parseInt(time[0])+12;
return time.join(":");

Single line code for calc time 12 hours to 24 hours
Any format of the input working fine
const convertTime12to24 = (time12h) => moment(time12h, 'hh:mm A').format('HH:mm');
console.log(convertTime12to24('06:30 pm'));
console.log(convertTime12to24('06:00 am'));
console.log(convertTime12to24('9:00 am'));
console.log(convertTime12to24('9pm'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.
function get24hTime(str) {
str = String(str).toLowerCase().replace(/\s/g, '');
var has_am = str.indexOf('am') >= 0;
var has_pm = str.indexOf('pm') >= 0;
// first strip off the am/pm, leave it either hour or hour:minute
str = str.replace('am', '').replace('pm', '');
// if hour, convert to hour:00
if (str.indexOf(':') < 0) str = str + ':00';
// now it's hour:minute
// we add am/pm back if striped out before
if (has_am) str += ' am';
if (has_pm) str += ' pm';
// now its either hour:minute, or hour:minute am/pm
// put it in a date object, it will convert to 24 hours format for us
var d = new Date("1/1/2011 " + str);
// make hours and minutes double digits
var doubleDigits = function(n) {
return (parseInt(n) < 10) ? "0" + n : String(n);
};
return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}
console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11

I needed this function for a project. I tried devnull69's but I was having some trouble, mostly because the string input is very specific for the am/pm section and I would've needed to change my validation. I messed around with Adrian P.'s jsfiddle and ended up with a version that seems to work better for a larger variety of date formats. Here is the fiddle: http://jsfiddle.net/u91q8kmt/2/.
Here is the function:
function ConvertTimeformat(format, str) {
var hours = Number(str.match(/^(\d+)/)[1]);
var minutes = Number(str.match(/:(\d+)/)[1]);
var AMPM = str.match(/\s?([AaPp][Mm]?)$/)[1];
var pm = ['P', 'p', 'PM', 'pM', 'pm', 'Pm'];
var am = ['A', 'a', 'AM', 'aM', 'am', 'Am'];
if (pm.indexOf(AMPM) >= 0 && hours < 12) hours = hours + 12;
if (am.indexOf(AMPM) >= 0 && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
if (format == '0000') {
return (sHours + sMinutes);
} else if (format == '00:00') {
return (sHours + ":" + sMinutes);
} else {
return false;
}
}

With this you can have the following:
Sample Input: 07:05:45PM
Sample Output: 19:05:45
function timeConversion(s) {
let output = '';
const timeSeparator = ':'
const timeTokenType = s.substr(s.length - 2 , 2).toLowerCase();
const timeArr = s.split(timeSeparator).map((timeToken) => {
const isTimeTokenType =
timeToken.toLowerCase().indexOf('am') > 0 ||
timeToken.toLowerCase().indexOf('pm');
if(isTimeTokenType){
return timeToken.substr(0, 2);
} else {
return timeToken;
}
});
const hour = timeArr[0];
const minutes = timeArr[1];
const seconds = timeArr[2];
const hourIn24 = (timeTokenType === 'am') ? parseInt(hour) - 12 :
parseInt(hour) + 12;
return hourIn24.toString()+ timeSeparator + minutes + timeSeparator + seconds;
}
Hope you like it !

Because all the answers so far seem to be verbose, here's a simple minimalist solution:
/* Convert h:mm a/p to H:mm
* i.e. 12 hour time to 24 hour time
* #param {string} time - h:mm a/p format
* #returns {string} time in H:mm format
*/
function to24HrTime(time) {
let [hr, min, ap] = time.toLowerCase().match(/\d+|[a-z]+/g) || [];
return `${(hr % 12) + (ap == 'am'? 0 : 12)}:${min}`;
}
['9:02 am',
'9:02 pm',
'9:02am',
'9:02pm',
'12:15 AM',
'12:01 PM',
].forEach(time => console.log(`${time} -> ${to24HrTime(time)}`));
That assumes the input string has a suitable format and values. A more robust version is:
/* Given 12 hr time, return24 hr time
* #param {string} time - time in format h:mm am/pm
* h must be in range 1 to 12
* mm must be in range 00 to 59
* am/pm is not case sensitive
* #returns {string} time in 24 hr format H:mm
* H in range 0 to 23
* mm in range 00 to 59
*
*/
function to24HrTime(time = new Date().toLocaleString('en',{hour:'numeric', minute:'2-digit', hour12:true})) {
let [hr, min, ap] = String(time).toLowerCase().match(/\d+|[a-z]+/g) || [];
// If time is valid, return reformatted time
// Otherwise return undefined
return /^([1-9]|1[0-2]):[0-5]\d\s?(am|pm)/i.test(time)? `${(hr%12)+(ap=='am'?0:12)}:${min}` : void 0;
}
// Examples
// Without arguments
console.log(`No args -> ${to24HrTime()}`);
// Valid input
['9:02 am',
'9:02 pm',
'9:02am',
'9:02pm',
'12:15 AM',
'12:01 PM',
// Invalid input
'12', // Missing mins & ap
'99:05 am', // hrs out of range
'0:05 am', // hrs out of range
'9:60 am', // mins out of range
'9:09 pp', // ap out of range
{}, // Random object
].forEach(time => console.log(`${time} -> ${to24HrTime(time)}`));

An extended version of #krzysztof answer with the ability to work on time that has space or not between time and modifier.
const convertTime12to24 = (time12h) => {
const [fullMatch, time, modifier] = time12h.match(/(\d?\d:\d\d)\s*(\w{2})/i);
let [hours, minutes] = time.split(':');
if (hours === '12') {
hours = '00';
}
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return `${hours}:${minutes}`;
}
console.log(convertTime12to24('01:02 PM'));
console.log(convertTime12to24('05:06 PM'));
console.log(convertTime12to24('12:00 PM'));
console.log(convertTime12to24('12:00 AM'));

based on meeting CodeSkill #1
validation of format should be another function :)
function convertTimeFrom12To24(timeStr) {
var colon = timeStr.indexOf(':');
var hours = timeStr.substr(0, colon),
minutes = timeStr.substr(colon+1, 2),
meridian = timeStr.substr(colon+4, 2).toUpperCase();
var hoursInt = parseInt(hours, 10),
offset = meridian == 'PM' ? 12 : 0;
if (hoursInt === 12) {
hoursInt = offset;
} else {
hoursInt += offset;
}
return hoursInt + ":" + minutes;
}
console.log(convertTimeFrom12To24("12:00 AM"));
console.log(convertTimeFrom12To24("12:00 PM"));
console.log(convertTimeFrom12To24("11:00 AM"));
console.log(convertTimeFrom12To24("01:00 AM"));
console.log(convertTimeFrom12To24("01:00 PM"));

Converting AM/PM Time string to 24 Hours Format.
Example 9:30 PM to 21:30
function get24HrsFrmAMPM(timeStr) {
if (timeStr && timeStr.indexOf(' ') !== -1 && timeStr.indexOf(':') !== -1) {
var hrs = 0;
var tempAry = timeStr.split(' ');
var hrsMinAry = tempAry[0].split(':');
hrs = parseInt(hrsMinAry[0], 10);
if ((tempAry[1] == 'AM' || tempAry[1] == 'am') && hrs == 12) {
hrs = 0;
} else if ((tempAry[1] == 'PM' || tempAry[1] == 'pm') && hrs != 12) {
hrs += 12;
}
return ('0' + hrs).slice(-2) + ':' + ('0' + parseInt(hrsMinAry[1], 10)).slice(-2);
} else {
return null;
}
}

//here is my solution.
function timeConversion(s) {
// Write your code here
let amPM = s.indexOf('AM') !== -1 ? 'AM' : 'PM';
let tString = s.toString().replace(/AM|PM/gi,'');
let splitTime = tString.split(':');
let h = splitTime[0];
let m = splitTime[1];
let sec = splitTime[2];
let twntyfr = amPM === 'PM' && parseInt(h) !== 12 ? parseInt(h)+12 : h;
if(parseInt(twntyfr) === 12 && amPM === 'AM') twntyfr = '00';
return twntyfr+':'+m+':'+sec;
}

HackerRank TimeConversion Solution
12-hour AM/PM format, to military (24-hour) time
function timeConversion(s) {
let time = 0
let hour = s.slice(0, 2)
let toD = s.slice(-2)
if (toD === 'AM' && hour == 12) {
time = `00${s.slice(2, s.length -2)}`
} else {
if (toD === 'PM' && hour < 12) {
time = `${Number(12 + parseInt(hour))}${s.slice(2, s.length - 2)}`
} else {
time = s.slice(0, s.length - 2)
}
}
return console.log(time)
}
timeConversion('12:00:17AM') // 00:00:17
timeConversion('09:21:33PM') // 21:21:33
timeConversion('12:43:53PM') // 12:43:53

function getDisplayDatetime() {
var d = new Date("February 04, 2011 19:00"),
hh = d.getHours(), mm = d.getMinutes(), dd = "AM", h = hh;
mm=(mm.toString().length == 1)? mm = "0" + mm:mm;
h=(h>=12)?hh-12:h;
dd=(hh>=12)?"PM":"AM";
h=(h == 0)?12:h;
var textvalue=document.getElementById("txt");
textvalue.value=h + ":" + mm + " " + dd;
}
</script>
</head>
<body>
<input type="button" value="click" onclick="getDisplayDatetime()">
<input type="text" id="txt"/>

dateFormat.masks.armyTime= 'HH:MM';
now.format("armyTime");

function convertTo24Hour(time) {
time = time.toUpperCase();
var hours = parseInt(time.substr(0, 2));
if(time.indexOf('AM') != -1 && hours == 12) {
time = time.replace('12', '0');
}
if(time.indexOf('PM') != -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
return time.replace(/(AM|PM)/, '');
}

date --date="2:00:01 PM" +%T
14:00:01
date --date="2:00 PM" +%T | cut -d':' -f1-2
14:00
var="2:00:02 PM"
date --date="$var" +%T
14:00:02

You could try this more generic function:
function from12to24(hours, minutes, meridian) {
let h = parseInt(hours, 10);
const m = parseInt(minutes, 10);
if (meridian.toUpperCase() === 'PM') {
h = (h !== 12) ? h + 12 : h;
} else {
h = (h === 12) ? 0 : h;
}
return new Date((new Date()).setHours(h,m,0,0));
}
Note it uses some ES6 functionality.

I've created a bit of an adaptation of script #devnull69 submitted. I felt for my application it would be more useful as a function that returned the value that I could, then use as a variable.
HTML
<input type="text" id="time_field" />
<button>Submit</submit>
jQuery
$(document).ready(function() {
function convertTime(time) {
var hours = Number(time.match(/^(\d\d?)/)[1]);
var minutes = Number(time.match(/:(\d\d?)/)[1]);
var AMPM = time.match(/\s(AM|PM)$/i)[1];
if((AMPM == 'PM' || AMPM == 'pm') && hours < 12) {
hours = hours + 12;
}
else if((AMPM == 'AM' || AMPM == "am") && hours == 12) {
hours = hours - 12;
}
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours < 10) {
sHours = "0" + sHours;
}
else if(minutes < 10) {
sMinutes = "0" + sMinutes;
}
return sHours + ":" + sMinutes;
}
$('button').click(function() {
alert(convertTime($('#time_field').val()));
});
});

single and easy js function for calc time meridian in real time
JS
function convertTime24to12(time24h) {
var timex = time24h.split(':');
if(timex[0] !== undefined && timex [1] !== undefined)
{
var hor = parseInt(timex[0]) > 12 ? (parseInt(timex[0])-12) : timex[0] ;
var minu = timex[1];
var merid = parseInt(timex[0]) < 12 ? 'AM' : 'PM';
var res = hor+':'+minu+' '+merid;
document.getElementById('timeMeridian').innerHTML=res.toString();
}
}
Html
<label for="end-time">Hour <i id="timeMeridian"></i> </label>
<input type="time" name="hora" placeholder="Hora" id="end-time" class="form-control" onkeyup="convertTime24to12(this.value)">

Typescript solution based off of #krzysztof-dÄ…browski 's answer
export interface HoursMinutes {
hours: number;
minutes: number;
}
export function convert12to24(time12h: string): HoursMinutes {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (hours === '12') {
hours = '00';
}
if (minutes.length === 1) {
minutes = `0${minutes}`;
}
if (modifier.toUpperCase() === 'PM') {
hours = parseInt(hours, 10) + 12 + '';
}
return {
hours: parseInt(hours, 10),
minutes: parseInt(minutes, 10)
};
}

Tested for all the use cases
function timeConversion(s) {
let h24;
let m24;
let sec24;
const splittedDate = s.split(":");
const h = parseInt(splittedDate[0], 10);
const m = parseInt(splittedDate[1], 10);
const sec = parseInt(splittedDate[2][0] + splittedDate[2][1], 10);
const meridiem = splittedDate[2][2] + splittedDate[2][3];
if (meridiem === "AM") {
if (h === 12) {
h24 = '00';
} else {
h24 = h;
if (h24 < 10) {
h24 = '0' + h24;
}
}
m24 = m;
sec24 = sec;
} else if (meridiem === "PM") {
if (h === 12) {
h24 = h
} else {
h24 = h + 12;
if (h24 < 10) {
h24 = '0' + h24;
}
}
m24 = m;
sec24 = sec;
}
if (m24 < 10) {
m24 = '0' + m24;
}
if (sec24 < 10) {
sec24 = '0' + sec24;
}
return h24 + ":" + m24 + ":" + sec24;
}
Here is the jsfiddle working example

Short ES6 code
const convertFrom12To24Format = (time12) => {
const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
const PM = period === 'PM';
const hours = (+sHours % 12) + (PM ? 12 : 0);
return `${('0' + hours).slice(-2)}:${minutes}`;
}
const convertFrom24To12Format = (time24) => {
const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
const period = +sHours < 12 ? 'AM' : 'PM';
const hours = +sHours % 12 || 12;
return `${hours}:${minutes} ${period}`;
}

I just solved this issue on HackerRank, so I'm here to share my result
function timeConversion(s) {
const isPM = s.indexOf('PM') !== -1;
let [hours, minutes, seconds] = s.replace(isPM ? 'PM':'AM', '').split(':');
if (isPM) {
hours = parseInt(hours, 10) + 12;
hours = hours === 24 ? 12 : hours;
} else {
hours = parseInt(hours, 10);
hours = hours === 12 ? 0 : hours;
if (String(hours).length === 1) hours = '0' + hours;
}
const time = [hours, minutes, seconds].join(':');
return time;
}
This works for inputs like 06:40:03AM.

function formatto24(date) {
let ampm = date.split(" ")[1];
let time = date.split(" ")[0];
if (ampm == "PM") {
let hours = time.split(":")[0];
let minutes = time.split(":")[1];
let seconds = time.split(":")[2];
let hours24 = JSON.parse(hours) + 12;
return hours24 + ":" + minutes + ":" + seconds;
} else {
return time;
}
}

Related

how to time convert 0200 , 0900 , 1600 to AM and PM

i have below code for time but.. when user my User enter 0800 , 1600 ,0230
like this time how to covert this time to AM and pm
function tConv24(time24) {
var ts = time24;
var H = +ts.substr(0, 2);
var h = (H % 12) || 12;
h = (h < 10)?("0"+h):h; // leading 0 at the left for 1 digit hours
var ampm = H < 12 ? " AM" : " PM";
ts = h + ts.substr(2, 3) + ampm;
return ts;
};
console.log(tConv24('0200'));
console.log(tConv24('0900'));
console.log(tConv24('1600'));
A plain JavaScript function might look like this, doing only text processing:
function f(s) {
var m = s.match(/^(\d\d)(\d\d)$/)
if (!m) { return null }
var hour = Number(m[1])
if (hour < 12) {
return `${hour}:${m[2]} AM`
}
return `${hour-12}:${m[2]} PM`
}
f('0800') // => "8:00 AM"
f('1630') // => "4:30 PM"
f('foo') // => null
Since you are using AngularJS you could wrap the existing date filter and use its formatter like so:
myAngularModule
.filter('t24', function($filter) {
return function(input) {
var m;
if (m = input.match(/^(\d\d)(\d\d)$/)) {
var now = new Date()
now.setHours(m[1])
now.setMinutes(m[2])
return $filter('date')(now, 'hh:mm a')
}
return 'invalid time'
}
})
...
<div>
You chose {{ theUserTime | t24 }}
</div>
function tConv24(time24) {
var ts = time24;
console.log(ts);
var H = +ts.substr(0, 2);
var h = (H % 12) || 12;
h = (h < 10)?("0"+h):h; // leading 0 at the left for 1 digit hours
var ampm = H < 12 ? " AM" : " PM";
ts = h + ':' + ts.substr(2, 3) + ampm;
return ts;
};
console.log(tConv24('0800'));
console.log(tConv24('1034'));
console.log(tConv24('0000'));
console.log(tConv24('1200'));
console.log(tConv24('2222'));
console.log(tConv24('2359'));

How to set Am and Pm for Clock [duplicate]

I have buttons with the names of big cities.
Clicking them, I want to get local time in them.
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = hours-2; //this is the distance from my local time
alert ('Toronto time: ' + hours + ' h'); //this works correctly
});
But how can I get AM or PM ?
You should just be able to check if hours is greater than 12.
var ampm = (hours >= 12) ? "PM" : "AM";
But have you considered the case where the hour is less than 2 before you subtract 2? You'd end up with a negative number for your hour.
Try below code:
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = (hours+24-2)%24;
var mid='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='pm';
}
alert ('Toronto time: ' + hours + mid);
});
You can use like this,
var dt = new Date();
var h = dt.getHours(), m = dt.getMinutes();
var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
Hopes this will be better with minutes too.
const now = new Date()
.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
.toLowerCase();
Basically you just need to put {hour12: true} and it's done.
result => now = "21:00 pm";
If hours is less than 12, it's the a.m..
var hours = new Date().getHours(), // this is local hours, may want getUTCHours()
am;
// adjust for timezone
hours = (hours + 24 - 2) % 24;
// get am/pm
am = hours < 12 ? 'a.m.' : 'p.m.';
// convert to 12-hour style
hours = (hours % 12) || 12;
Now, for me as you didn't use getUTCHours, it is currently 2 hours after
hours + ' ' + am; // "6 p.m."
very interesting post. in a function that take a date in parameter it can appear like that :
function hourwithAMPM(dateInput) {
var d = new Date(dateInput);
var ampm = (d.getHours() >= 12) ? "PM" : "AM";
var hours = (d.getHours() >= 12) ? d.getHours()-12 : d.getHours();
return hours+' : '+d.getMinutes()+' '+ampm;
}
with date.js
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
you can write like this
new Date().toString("hh:mm tt")
cheet sheet is here format specifiers
tt is for AM/PM
Try this:
h = h > 12 ? h-12 +'PM' : h +'AM';
The best way without extensions and complex coding:
date.toLocaleString([], { hour12: true});
How do you display javascript datetime in 12 hour AM/PM format?
here is get time i use in my code
let current = new Date();
let cDate = current.getDate() + '-' + (current.getMonth() + 1) + '-' + current.getFullYear();
let hours = current.getHours();
let am_pm = (hours >= 12) ? "PM" : "AM";
if(hours >= 12){
hours -=12;
}
let cTime = hours + ":" + current.getMinutes() + ":" + current.getSeconds() +" "+ am_pm;
let dateTime = cDate + ' ' + cTime;
console.log(dateTime); // 1-3-2021 2:28:14 PM
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;
return timewithampm;
var dt = new Date();
var h = dt.getHours(),
m = dt.getMinutes();
var time;
if (h == 12) {
time = h + ":" + m + " PM";
} else {
time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
}
//var time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
console.log(`CURRENT TIME IS ${time}`);
This will work for everytime,
function Timer() {
var dt = new Date()
if (dt.getHours() >= 12){
ampm = "PM";
} else {
ampm = "AM";
}
if (dt.getHours() < 10) {
hour = "0" + dt.getHours();
} else {
hour = dt.getHours();
}
if (dt.getMinutes() < 10) {
minute = "0" + dt.getMinutes();
} else {
minute = dt.getMinutes();
}
if (dt.getSeconds() < 10) {
second = "0" + dt.getSeconds();
} else {
second = dt.getSeconds();
}
if (dt.getHours() > 12) {
hour = dt.getHours() - 12;
} else {
hour = dt.getHours();
}
if (hour < 10) {
hour = "0" + hour;
} else {
hour = hour;
}
document.getElementById('time').innerHTML = hour + ":" + minute + ":" + second + " " + ampm;
setTimeout("Timer()", 1000);
}
Timer()
<div id="time"></div>

Jquery function to Increment one hours based on time input string

I have string value in this format.
9:00 am
i want it to be like this.
9:00 am - 10:00 am
second hour must be 1 greater then first one. for example if time is
7:00 am then it should be 7:00 am - 8:00 am
how can i do that using jquery?
i tried this but its not working as it works now.
var time= "9:00 am"
var nexttime=time.setHours(time.getHours()+1)
alert(nexttime);
getting error of
time.getHours is not a function
You can try this :
function increaseTimeByOne(timeStr) {
var splitedTimeStr = timeStr.split(':');
var hours = parseInt(splitedTimeStr[0]);
var meridiem = splitedTimeStr[1].split(" ")[1];
var minutes = splitedTimeStr[1].split(" ")[0];
var nextHours = (hours + 1);
var nextMeridiem;
if (hours >= 11) {
if (meridiem.toLowerCase() == "am") {
nextMeridiem = "pm";
} else if (meridiem.toLowerCase() == "pm") {
nextMeridiem = "am";
}
if (nextHours > 12) {
nextHours = nextHours - 12;
}
} else {
nextMeridiem = meridiem;
}
return nextHours + ":" + minutes + " " + nextMeridiem;
}
and using above function as
var timestr="9:00 am";
var next_hour = increaseTimeByOne(timeStr);
alert(next_hour);
refer this
var time=new Date();
time.setHours(9, 00, 00);
var nexttime=(time.getHours()+1);
alert(nexttime);
// to get hrs mins and seconds
var nexttime=(time.getHours()+1) +":"+time.getMinutes()+":"+time.getSeconds();
YOu can make your time string like:
function increaseTimeByOne(t) {
var s = t.split(':');
var n = parseInt(s[0], 10);
var nt = (n + 1) + ":00 ";
var ampm = n >= 11 ? "pm" : "am";
return t + " - " + nt + ampm;
}
console.log(increaseTimeByOne('9:00 am'));
console.log(increaseTimeByOne('11:00 am'));
console.log(increaseTimeByOne('12:00 pm'));

How to convert the time from ''hh:mm:ss' format to an 'Hourly' format using jquery/JS [duplicate]

How do you display a JavaScript datetime object in the 12 hour format (AM/PM)?
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
console.log(formatAMPM(new Date));
If you just want to show the hours then..
var time = new Date();
console.log(
time.toLocaleString('en-US', { hour: 'numeric', hour12: true })
);
Output : 7 AM
If you wish to show the minutes as well then...
var time = new Date();
console.log(
time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
);
Output : 7:23 AM
Here's a way using regex:
console.log(new Date('7/10/2013 20:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
console.log(new Date('7/10/2013 01:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
This creates 3 matching groups:
([\d]+:[\d]{2}) - Hour:Minute
(:[\d]{2}) - Seconds
(.*) - the space and period (Period is the official name for AM/PM)
Then it displays the 1st and 3rd groups.
WARNING: toLocaleTimeString() may behave differently based on region / location.
If you don't need to print the am/pm, I found the following nice and concise:
var now = new Date();
var hours = now.getHours() % 12 || 12; // 12h instead of 24h, with 12 instead of 0.
This is based off #bbrame's answer.
As far as I know, the best way to achieve that without extensions and complex coding is like this:
date.toLocaleString([], { hour12: true});
Javascript AM/PM Format
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date and time as a string.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="fullDateTime()">Try it2</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function myFunction() {
var d = new Date();
var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' });
document.getElementById("demo").innerHTML = n;
}
function fullDateTime() {
var d = new Date();
var n = d.toLocaleString([], { hour12: true});
document.getElementById("demo2").innerHTML = n;
}
</script>
</body>
</html>
I found this checking this question out.
How do I use .toLocaleTimeString() without displaying seconds?
In modern browsers, use Intl.DateTimeFormat and force 12hr format with options:
let now = new Date();
new Intl.DateTimeFormat('default',
{
hour12: true,
hour: 'numeric',
minute: 'numeric'
}).format(now);
// 6:30 AM
Using default will honor browser's default locale if you add more options, yet will still output 12hr format.
Use Moment.js for this
Use below codes in JavaScript when using moment.js
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
The format() method returns the date in specific format.
moment(new Date()).format("YYYY-MM-DD HH:mm"); // 24H clock
moment(new Date()).format("YYYY-MM-DD hh:mm A"); // 12H clock (AM/PM)
moment(new Date()).format("YYYY-MM-DD hh:mm a"); // 12H clock (am/pm)
My suggestion is use moment js for date and time operation.
https://momentjs.com/docs/#/displaying/format/
console.log(moment().format('hh:mm a'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Updated for more compression
const formatAMPM = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'pm' : 'am';
hours %= 12;
hours = hours || 12;
minutes = minutes < 10 ? `0${minutes}` : minutes;
const strTime = `${hours}:${minutes} ${ampm}`;
return strTime;
};
console.log(formatAMPM(new Date()));
use dateObj.toLocaleString([locales[, options]])
Option 1 - Using locales
var date = new Date();
console.log(date.toLocaleString('en-US'));
Option 2 - Using options
var options = { hour12: true };
console.log(date.toLocaleString('en-GB', options));
Note: supported on all browsers but safari atm
Short RegExp for en-US:
var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"
Please find the solution below
var d = new Date();
var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
return d.getDate() + ' / ' + d.getMonth() + ' / ' + d.getFullYear() + ' ' + hour + ':' + d.getMinutes() + ' ' + amOrPm;
It will return the following format like
09:56 AM
appending zero in start for the hours as well if it is less than 10
Here it is using ES6 syntax
const getTimeAMPMFormat = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0' + hours : hours;
// appending zero in the start if hours less than 10
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ':' + minutes + ' ' + ampm;
};
console.log(getTimeAMPMFormat(new Date)); // 09:59 AM
I fount it's here it working fine.
var date_format = '12'; /* FORMAT CAN BE 12 hour (12) OR 24 hour (24)*/
var d = new Date();
var hour = d.getHours(); /* Returns the hour (from 0-23) */
var minutes = d.getMinutes(); /* Returns the minutes (from 0-59) */
var result = hour;
var ext = '';
if(date_format == '12'){
if(hour > 12){
ext = 'PM';
hour = (hour - 12);
result = hour;
if(hour < 10){
result = "0" + hour;
}else if(hour == 12){
hour = "00";
ext = 'AM';
}
}
else if(hour < 12){
result = ((hour < 10) ? "0" + hour : hour);
ext = 'AM';
}else if(hour == 12){
ext = 'PM';
}
}
if(minutes < 10){
minutes = "0" + minutes;
}
result = result + ":" + minutes + ' ' + ext;
console.log(result);
and plunker example here
Check out Datejs. Their built in formatters can do this: http://code.google.com/p/datejs/wiki/APIDocumentation#toString
It's a really handy library, especially if you are planning on doing other things with date objects.
<script>
var todayDate = new Date();
var getTodayDate = todayDate.getDate();
var getTodayMonth = todayDate.getMonth()+1;
var getTodayFullYear = todayDate.getFullYear();
var getCurrentHours = todayDate.getHours();
var getCurrentMinutes = todayDate.getMinutes();
var getCurrentAmPm = getCurrentHours >= 12 ? 'PM' : 'AM';
getCurrentHours = getCurrentHours % 12;
getCurrentHours = getCurrentHours ? getCurrentHours : 12;
getCurrentMinutes = getCurrentMinutes < 10 ? '0'+getCurrentMinutes : getCurrentMinutes;
var getCurrentDateTime = getTodayDate + '-' + getTodayMonth + '-' + getTodayFullYear + ' ' + getCurrentHours + ':' + getCurrentMinutes + ' ' + getCurrentAmPm;
alert(getCurrentDateTime);
</script>
Hopefully this answer is a little more readable than the other answers (especially for new comers).
Here's the solution I've implemented in some of my sites for informing the last time the site code was modified. It implements AM/PM time through the options parameter of date.toLocaleDateString (see related Mozilla documentation).
// Last time page code was updated/changed
const options = {
year: "numeric",
month: "long",
weekday: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: true // This is the line of code we care about here
/*
false: displays 24hs format for time
true: displays 12, AM and PM format
*/
};
let last = document.lastModified;
let date = new Date(last);
let local = date.toLocaleDateString("en-US", options);
let fullDate = `${local}`;
document.getElementById("updated").textContent = fullDate;
Which output is in the format:
Saturday, May 28, 2022, 8:38:50 PM
This output is then displayed in the following HTML code:
<p>Last update: <span id="updated">_update_date_goes_here</span></p>
NOTE: In this use case, document.lastModified has some weird behaviors depending if it's run locally or on a external server (see this Stack Overflow question). Though it works correctly when I run it in my GitHub page (you should see it in action in the site at the footer).
Here is another way that is simple, and very effective:
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = new Array(11);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');
document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());
</script></div><!-- #time -->
you can determine am or pm with this simple code
var today=new Date();
var noon=new Date(today.getFullYear(),today.getMonth(),today.getDate(),12,0,0);
var ampm = (today.getTime()<noon.getTime())?'am':'pm';
try this
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? "pm" : "am";
function formatTime( d = new Date(), ampm = true )
{
var hour = d.getHours();
if ( ampm )
{
var a = ( hour >= 12 ) ? 'PM' : 'AM';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
}
var hour = checkDigit(hour);
var minute = checkDigit(d.getMinutes());
var second = checkDigit(d.getSeconds());
// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
return ( ampm ) ? `${hour}:${minute}:${second} ${a}` : `${hour}:${minute}:${second}`;
}
function checkDigit(t)
{
return ( t < 10 ) ? `0${t}` : t;
}
document.querySelector("#time1").innerHTML = formatTime();
document.querySelector("#time2").innerHTML = formatTime( new Date(), false );
<p>ampm true: <span id="time1"></span> (default)</p>
<p>ampm false: <span id="time2"></span></p>
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
var meridian = h >= 12 ? "PM" : "AM";
h = h % 12;
h = h ? h : 12;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
var strTime = h + ":" + m + ":" + s + " " + meridian;
document.getElementById('time').innerText = strTime;
setTimeout(startTime, 1000);
}
startTime();
<h1 id='time'></h1>
If you have time as string like so var myTime = "15:30",
then you can use the following code to get am pm.
var hour = parseInt(myTime.split(":")[0]) % 12;
var timeInAmPm = (hour == 0 ? "12": hour ) + ":" + myTime.split(":")[1] + " " + (parseInt(parseInt(myTime.split(":")[0]) / 12) < 1 ? "am" : "pm");
var d = new Date();
var hours = d.getHours() % 12;
hours = hours ? hours : 12;
var test = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][(d.getMonth() + 1)] + " " +
("00" + d.getDate()).slice(-2) + " " +
d.getFullYear() + " " +
("00" + hours).slice(-2) + ":" +
("00" + d.getMinutes()).slice(-2) + ":" +
("00" + d.getSeconds()).slice(-2) + ' ' + (d.getHours() >= 12 ? 'PM' : 'AM');
document.getElementById("demo").innerHTML = test;
<p id="demo" ></p>
<h1 id="clock_display" class="text-center" style="font-size:40px; color:#ffffff">[CLOCK TIME DISPLAYS HERE]</h1>
<script>
var AM_or_PM = "AM";
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
h = twelve_hour_time(h);
m = checkTime(m);
s = checkTime(s);
document.getElementById('clock_display').innerHTML =
h + ":" + m + ":" + s +" "+AM_or_PM;
var t = setTimeout(startTime, 1000);
}
function checkTime(i){
if(i < 10){
i = "0" + i;// add zero in front of numbers < 10
}
return i;
}
// CONVERT TO 12 HOUR TIME. SET AM OR PM
function twelve_hour_time(h){
if(h > 12){
h = h - 12;
AM_or_PM = " PM";
}
return h;
}
startTime();
</script>
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;
var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
return dateTime;
}
Here my solution
function getTime() {
var systemDate = new Date();
var hours = systemDate.getHours();
var minutes = systemDate.getMinutes();
var strampm;
if (hours >= 12) {
strampm= "PM";
} else {
strampm= "AM";
}
hours = hours % 12;
if (hours == 0) {
hours = 12;
}
_hours = checkTimeAddZero(hours);
_minutes = checkTimeAddZero(minutes);
console.log(_hours + ":" + _minutes + " " + strampm);
}
function checkTimeAddZero(i) {
if (i < 10) {
i = "0" + i
}
return i;
}
const formatAMPM = (date) => {
try {
let time = date.split(" ");
let hours = time[4].split(":")[0];
let minutes = time[4].split(":")[1];
hours = hours || 12;
const ampm = hours >= 12 ? " PM" : " AM";
minutes = minutes < 10 ? `${minutes}` : minutes;
hours %= 12;
const strTime = `${hours}:${minutes} ${ampm}`;
return strTime;
} catch (e) {
return "";
}
};
const startTime = "2021-12-07T17:00:00.073Z"
formatAMPM(new Date(startTime).toUTCString())
This is the easiest Way you can Achieve this using ternary operator or you can also use if else instead !
const d = new Date();
let hrs = d.getHours();
let m = d.getMinutes();
// Condition to add zero before minute
let min = m < 10 ? `0${m}` : m;
const currTime = hrs >= 12 ? `${hrs - 12}:${min} pm` : `${hrs}:${min} am`;
console.log(currTime);
Or just simply do the following code:
<script>
time = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt_clock').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(function(){time()}, 0);
}
time2 = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
if (h>12) {
document.getElementById('txt_clock_stan').innerHTML = h-12 + ":" + m + ":" + s;
}
var t = setTimeout(function(){time2()}, 0);
}
time3 = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if (h>12) {
document.getElementById('hour_line').style.width = h-12 + 'em';
}
document.getElementById('minute_line').style.width = m + 'em';
document.getElementById('second_line').style.width = s + 'em';
var t = setTimeout(function(){time3()}, 0);
}
checkTime = function(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>

javascript, jquery time format

I have a question, how can I change time from 24hr format to 12, the easiest way, in javascript or Jquery .
This is what I have :
TempDate = $.datepicker.formatDate('MM dd, yy', TempDate);
var ChangeDate = TempDate + " " + TradeTime;
now TradeTime= 15:59 , but I wanna be 3:59PM
What is the easiest way , or can I use datapicker or to force this format in the same time with date.
Thanks
I'm afraid you will just have to do it manually, quick n dirty, for now ;)
function to12Hrs(strHrs, strMin) {
var hrs = Number(strHrs);
var min = Number(strMin);
var ampm = "am";
if(isNaN(hrs) || isNaN(min) || hrs > 23 || hrs < 0) {
throw ("Invalid Date " + str24Hrs);
}
if(hrs >= 12) {
hrs = (hrs - 12) || 12;
ampm = "pm";
}
var strHr = (hrs < 10) ? "0".concat(hrs) : hrs;
var strMin = (min < 10) ? "0".concat(min) : min;
return (strHr + ":" + strMin + ampm);
}
var arr = "12:30".split(":");
alert(to12Hrs(arr[0], arr[1])); // 12:30pm
arr = "11:00".split(":");
alert(to12Hrs(arr[0], arr[1])); // 11:00am
arr = "02:00".split(":");
alert(to12Hrs(arr[0], arr[1])); // 02:00am
arr = "20:00".split(":");
alert(to12Hrs(arr[0], arr[1])); // 08:00pm
This helped me :
TradeTime = ("" + TradeTime).split(":",2);
if (TradeTime[0] < 12)
{
a_p = "AM";
}
else
{
a_p = "PM";
}
if (TradeTime[0] == 0)
{
TradeTime[0] = 12;
}
if (TradeTime[0] > 12)
{
TradeTime[0] = TradeTime[0] - 12;
}

Categories

Resources