How do you display javascript datetime in 12 hour AM/PM format?

How do you display a javascript datetime object in the 12 hour format (AM/PM)?

-------------Problems Reply------------

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;

You can also consider using something like date.js:

<script type="text/javascript" src=""></script>

(function ()
document.write(new Date().toString("hh:mm tt"));

Here's a way using regex:

new Date('7/10/2013 20:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
"8:12 PM"
new Date('7/10/2013 01:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
"1:12 AM"

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.

Check out Datejs. Their built in formatters can do this:

It's a really handy library, especially if you are planning on doing other things with date objects.

Short RegExp for en-US:

var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"

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 -->

Or just simply do the following code:

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;

You can get am the current time or passed date time to AM PM format through following function.

Live Output with Example

function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()

if (minutes < 10)
minutes = "0" + minutes;

var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
if (hours == 0) {
hours = 12;
var current_time = hours + ":" + minutes + " " + suffix;
show_message("Current Your System Time is : " + current_time);

Category:javascript Views:2 Time:2012-01-17

Related post

  • Jquery/javascript datetime 2009-08-22

    i want to convert this string 23/08/2009 12:05:00 to javascript datetime how can i do it? --------------Solutions------------- I think this can help you Theres a getDateFromFormat() function that you can twea

  • select maximum score grouped by date, display full datetime 2009-09-21

    Gday, I have a table that shows a series of scores and datetimes those scores occurred. I'd like to select the maximum of these scores for each day, but display the datetime that the score occurred. I am using an Oracle database (10g) and the table i

  • How to display all datetime on website in user's GMT locale? 2010-08-10

    I store all datetime values as unix timestamp. Registered users can set personal GMT locale in their profile. What should I do to display all datetime on website in user's GMT locale? Thank you --------------Solutions------------- There's no such thi

  • Javascript. Convert datetime to pretty date. Strange format 2011-08-25

    How can I, using Javascript, convert the below data to pretty format, i.e. "2 days ago"? 2011-08-11 16:12:31.119218+0000 What is this format called? Thankful for all input! --------------Solutions------------- I think that format is called "fuzzy tim

  • Display Javascript "same origin policy" violations 2011-09-01

    I'm developing a mobile app which runs a simple HTTP server and a WebView. The WebView displays an external website which should access the server via javascript (GET). Unfortunately this doesn't work and I assume it's due to the same origin policy b

  • Why can't display a DateTime object 2012-01-10

    $date = new DateTime(2011-10-05); echo $date->format('Y-m-d H:i:s'); Running the above code, the page is displayed nothing. Just wondering is there anything wrong on the code and I used the PHP5 (Version 5.3.0). Can anyone help me? Thanks in advan

  • Displaying current datetime in MessageBox in C# 2012-01-13

    I know this is very trivial but I can't seem to find the answer as I have never done C#. Searched on Google but in vain. I am trying to display current datetime in MessageBox in C# but I get following error Cannot convert datetime into string. Here i

  • Why doesn't DateTime.ToShortTimeString() respect the Short Time format in "Regional and Language Settings"? 2009-08-18

    I have run into an issue that is probably due to my mis-understanding of how the DateTime.ToShortTimeString() method works. When formatting time strings with this function, I was assuming that it would respect the "Short Time" setting in Windows 7's

  • Is there a functionality in JavaScript to convert values into specific locale formats? 2011-03-15

    Is there a built in function of JavaScript to convert a string into a particular locale (Euro in my case)? E.g. 50.00 should get converted to 50,00 €. --------------Solutions------------- 50.00 is a unit-less value. The best you can do is convert 50.

  • JavaScript won't parse GMT Date/Time Format 2009-08-20

    I'm trying to get JavaScript to parse a date and time format for me, with the eventual aim of telling me the days passed since that date and the time right now (locally). Unfortunately, the date format I have to work with (it's from a JSON response w

  • javascript - string to date - php iso string format 2010-12-15

    I have a date in format of: 2010-11-30T08:32:22+0000 2010-11-27T20:59:17+0000 coming from a feed, in string format to javascript, now I want to convert it to a Date object. How can I do it in javascript? --------------Solutions------------- Perhaps i

  • What is a Javascript ToolTip library that can do HTML formatting, positioning, and is reliable? 2011-04-18

    What is a good Javascript tooltip library that can do HTML formatting and positioning? jQuery tooltip plugin is said to be reliable but can it do HTML and positioning (such as bottom-center)? jQuery Tools's Tooltip can do it except it is only about 9

  • Javascript toLocaleString does not use the correct format 2012-02-21

    It seems to me that javascript's number toLocaleString() and .NET ToString() format numbers differently. toLocaleString() seems to ignore the language I set in Tools/Internet Options/Languages. For example, to test spanish support I made sure only Sp

  • Change display of DateTime in MVC 2011-05-18

    <%= Html.TextBoxFor(m => m.Trx.TradeDate, new { @class = "economicTextBox", propertyName = "Trx.TradeDate", dontRegisterNewIndication = true })%> Since this is a TextBoxFor, I can't just change the way it's displayed (I don't think?), becaus

  • ExtJs 4 Displaying WCF DateTime 2011-09-07

    I can't figure out how convert the datetime that wcf outputs into a datetime that ExtJs can use. I have found lots of articles about this but they are all for ExtJs 3 and I couldn't get it to work with 4. I did find this code but I don't know how I c

  • javascript dateTime - the same format as server 2012-03-01

    I have an ajax call, which returns datetime. Javascript displays it using client timezone. I not need in any client timezone, I want to show datetime the same as server return. Is it possible? I get date via: var d = eval('new' + date.replace(/\//g,

  • Best way to display Javascript/Div based hover windows? 2009-02-22

    I'm talking about the Ibox sort. I.e, user clicks a link and a small javascript based div hovers up containing a small form or such. I will want to give users a <script> tag which they would place in their website. Then, they would put the requ

  • Display javascript value within HTML body 2009-05-26

    i have the following relevant code in the header of my html doc: test1.value ="Date1"); And I'm trying to display the test1 value in the body of my html doc. It displays when i use: <input type="text" id="test1" />

  • Is there a way to display javascript content in blog feeds 2009-11-13

    Does RSS/Atom have a semi-official method of including active (read:javascript) content in it's items? I know about RSS enclosures, but I'm presuming that's for true multimedia - ie mp3 and the likes. Say I have a bit of remote javascript I want to i

Copyright (C), All Rights Reserved.

processed in 0.388 (s). 11 q(s)