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>
I am trying to get Days,hours from two dates.I searched for the solution and try some code like below but none of them returns the correct days with hours like 2 days ,3 hours.My fields values are like :
d1 = '2014-10-09 08:10:56';
d2 ='2014-11-09 10:10:56';
var dateDiff = function ( d1, d2 ) {
var diff = Math.abs(d1 - d2);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000) + " days";
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000) + " hours";
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000) + " minutes";
} else {
return "< 1 minute";
}
};
function DateDiff(date1, date2) {
var msMinute = 60*1000,
msDay = 60*60*24*1000,
c = new Date(), /* now */
d = new Date(c.getTime() + msDay - msMinute);
return Math.floor(((date2 - date1) % msDay) / msMinute) + ' full minutes between'; //Convert values days and return value
}
what am i doing wrong.Any help thanks
Have you converted d1, d2 to Date object before calling the function dateDiff? Because if you haven't, this line var diff = Math.abs(d1 - d2); won't work as expected.
UPDATE:
I'am assuming your d1 and d2 are in "Y-m-d H:S:M" format, try this:
function parseDate(str){
var tmp = str.split(' ');
var d = tmp[0].split('-');
var t = tmp[1].split(':');
return new Date(d[0], d[1]-1, d[2], t[0], t[1], t[2]);
}
function dateDiff(d1, d2){
d1 = parseDate(d1);
d2 = parseDate(d2);
// ...
// Your code continues
}
I wish I could make it simpler... But this seems to work.
var d1 = '2014-10-09 08:10:58',
d2 ='2015-10-09 08:10:50';
function getDateFromString(str) {
var regexDate = /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/,
values = regexDate.exec(str);
return new Date(values[1], values[2], values[3], values[4], values[5], values[6]);
}
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
function dateDiff(d1,d2){
if (d1.getTime() > d2.getTime()) {
var oldD1 = d1;
d1 = d2;
d2 = oldD1;
}
var yearDiff = d2.getFullYear() - d1.getFullYear(),
monthDiff = d2.getMonth() - d1.getMonth(),
dayDiff = d2.getDate() - d1.getDate(),
hourDiff = d2.getHours() - d1.getHours(),
minDiff = d2.getMinutes() - d1.getMinutes(),
secDiff = d2.getSeconds() - d1.getSeconds();
if (secDiff < 0) {
secDiff = 60 + secDiff;
minDiff--;
}
if (minDiff < 0) {
minDiff = 60 + minDiff;
hourDiff--;
}
if (hourDiff < 0) {
hourDiff = 24 + hourDiff;
dayDiff--;
}
if (dayDiff < 0) {
var days = daysInMonth(date2.getMonth(), date2.getFullYear());
dayDiff = days + dayDiff;
monthDiff--;
}
if (monthDiff < 0) {
monthDiff = 12 + monthDiff;
yearDiff--;
}
var diff = yearDiff > 0 ? yearDiff + " years " : "";
diff += monthDiff > 0 ? monthDiff + " months " : "";
diff += dayDiff > 0 ? dayDiff + " days " : "";
diff += hourDiff > 0 ? hourDiff + " hours " : "";
diff += minDiff > 0 ? minDiff + " minutes " : "";
diff += secDiff > 0 ? secDiff + " seconds " : "";
return diff;
}
var date1 = getDateFromString(d1),
date2 = getDateFromString(d2)
document.getElementById('test').innerHTML += date1 + "<br />" + date2;
document.getElementById('test').innerHTML += "<br />" + dateDiff(date1, date2);
console.log(dateDiff(date1, date2));
See JSFiddle
It works in all browsers.
Try this - >
d1 = '2014-10-09 08:10:56';
d2 = '2014-11-09 10:10:56';
var diff = dateDiff(d1,d2);
alert(diff);
function splitDate(d1){
var dSplit = d1.split(' ');
d = dSplit[0] + 'T' + dSplit[1];
return d;
}
function dateDiff(d1,d2){
d1 = splitDate(d1);
d2 = splitDate(d2);
var date1 = new Date(d1);
var date2 = new Date(d2);
var dateDiff = new Date(date2 - date1);
var diff = "Month " + dateDiff.getMonth() + ", Days " + dateDiff.getDay() + ", Hours " + dateDiff.getHours();
return diff;
}
I am assuming you want the difference between 2 dates.
var dateDiff = function(d1/*String*/, d2/*String*/){
var date1 = new Date(d1);
var date2 = new Date(d2);
var result = {
negative:false
};
var diff = date1-date2;
if(diff<0){
result.negative = true;
diff*=-1;
}
result.milliseconds = diff%1000;
diff-=result.milliseconds;
diff/=1000;
result.seconds = diff%60;
diff-=result.seconds
diff/=60;
result.minutes = diff%60;
diff-=result.minutes
diff/=60;
result.hours = diff%24;
diff-=result.hours
result.days= diff/=24;
//And so on
return result;
}
I'm not sure if I really understood but I think this is what you want : http://jsfiddle.net/OxyDesign/927n0L34/
JS
var difference = toDaysAndHours('2014-10-09 08:10:56','2014-11-09 10:10:56');
function toDaysAndHours(d1,d2){
var dif, hours, days, difString = '';
d1 = new Date(d1);
d2 = new Date(d2);
dif = Math.abs(d1 - d2);
hours = (dif/(1000*60*60)).toFixed(0);
days = (hours/24).toFixed(0);
hours = hours - days*24;
difString = days+' days, '+hours+' hours';
return difString;
}
In the first function you are using strings not dates. to properly initialize a date use the constructor, as in:
d1 = new Date('2014-10-09 08:10:56')
d2 = new Date('2014-11-09 10:10:56')
Then on d1 and d2 you can use all of the get*/set* methods specified here: http://www.w3schools.com/jsref/jsref_obj_date.asp
While I got distracted writing the answer, I see others have said similar things, but I will add this:
The data object approach is good for understanding things, but if you want to save time use http://momentjs.com/ or a similar module to save time and mistakes.
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;
}