show javascript date in am pm format

How to Show JavaScript Date in 12 Hour AM/PM Format

JavaScript dates are objects that store information about year, month, date, hour, minutes and seconds. It supports numerous methods such as getFullYear(), getFullMonth(), etc. to retrieve information about the year, month, etc. of the date object. But sometimes you may need to simply show JavaScript date in 12 hour AM/PM format. There is no built-in function for this purpose. So in this article, we will learn how to do this.


How to Show JavaScript Date in 12 Hour AM/PM Format

Here is a simple JS function to easily return any JS date in 12 hour AM/PM format.

function format_date(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(format_date(new Date));

Let us look at the above code. Our function accepts JS date as input. First, we retrieve its hour information using getHours() method. Then we get its minutes information using getMinutes() function. Using the hour information we determine whether it is AM or PM. If hours>12 it is PM, else AM.

By default, the hour information returned by getHours() is in 24-hour format. We convert it to 12-hour format by doing modulus division by 12. We also convert hours to 12 if it is zero, else leave it as it is.

Lastly, we prepend zero to minutes if it is less than 10.

Lastly, we concatenate the hours, minutes and am/pm string to get our JS time in AM/PM format. Its output will be something like ’08:30 AM’.

Another easy way to do this is to use toLocaleString() function, as shown below.

var time = new Date();
console.log(
  time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
);

Its output will be something like ’08:30 AM’.

In this article, we have learnt how to show JavaScript time in AM/PM format.

Also read:

How to Get HTML Element’s Width & Height
How to Call Parent Window Function from IFrame
How to Get Cookie By Name in JavaScript
How to Find Max Value of Attribute in Array of JS Objects
How to Get Last Item of JS Array

Leave a Reply

Your email address will not be published. Required fields are marked *