24

When I use the "getHour()" method in javascript, it displays the military time format. I need it to display the hour in numbers between 1-12 instead. Can anybody tell me how to do this? Here is the code I am using:

function updateclock()
{

    var time = new Date();
    var todisplay = '';

    if (time.getHours() < 10) todisplay += time.getHours();
    else todisplay += time.getHours();

    if (time.getMinutes() < 10) todisplay += ':0' + time.getMinutes();
    else todisplay += ':' + time.getMinutes();

    document.getElementById("clock").innerHTML = todisplay;
}
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Tony Wilkerson
  • 351
  • 1
  • 2
  • 4

10 Answers10

48

Why not do it the brief way? Math, people! :)

// returns the hours number for a date, between 1 and 12
function hours12(date) { return (date.getHours() + 24) % 12 || 12; }
mcw
  • 3,500
  • 1
  • 31
  • 33
  • 10
    Where is the math! (X + n*12) % 12 ==> X % 12 shorten your answer to. function hours12(date) { return date.getHours() %12 || 12; } – Waleed A.K. May 18 '16 at 03:14
  • You know, I feel like when I first wrote the answer there was a good reason to have the +24. But doing a re-test of the code in Chrome, and checking the API doc (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours), you are correct - you should be safe leaving it out. – mcw May 27 '16 at 13:37
  • Nope - but only because of the trailing `|| 12`. I'm not clear though on what you'd expect noon to show as if 0 is specifically midnight. I've never heard of a 12-hour system that uses "0 pm" as noon. – mcw Oct 09 '16 at 18:03
  • I suppose the provided answer is most feasible and correct. Does @WaleedA.K. trying to say x%12 will work? wouldn't it give 0 in midnight by using x%12 only. – Anant Nov 08 '16 at 08:32
  • 1
    @Anant - no, @Waleed A.K. was pointing out that, mathematically, `(x + 24) % 12` is equivalent to `x % 12`. So the first part of my answer, which I left unedited, could be simplified by removing the `+ 24`. The `|| 12` is still necessary exactly for the reason you suggest - you will get 0 for midnight/noon without it. – mcw Nov 29 '16 at 01:56
33

This will correct 13 - 24 back to the range 1 - 12, and 0 back to 12:

var hours = time.getHours();
if (hours > 12) {
    hours -= 12;
} else if (hours === 0) {
   hours = 12;
}

Also, you need to stop repeating yourself in your code. Call time.getHours() and time.getMinutes() and store their values just once each, and then worry about adding the leading zeroes, e.g.:

function updateclock() {

    function pad(n) {
         return (n < 10) ? '0' + n : n;
    }

    var time = new Date();
    var hours = time.getHours();
    var minutes = time.getMinutes();

    if (hours > 12) {
        hours -= 12;
    } else if (hours === 0) {
        hours = 12;
    }

    var todisplay = pad(hours) + ':' + pad(minutes);
    document.getElementById("clock").innerHTML = todisplay;
}
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 1
    @jbabey no, that's just the [DRY Principle](http://en.wikipedia.org/wiki/Don't_repeat_yourself). [Memoization](http://en.wikipedia.org/wiki/Memoization) is the practise of caching previously returned results and returning those instead of doing the work to calculate them again next time the same parameters are supplied. – Alnitak May 11 '12 at 18:50
  • right, you're not calculating .getHours() or .getMinutes() again. – jbabey May 11 '12 at 18:53
  • @jbabey no, it's not memoization if you're just storing _temporary_ values _inside_ a function. See the link I posted in the previous comment. – Alnitak May 11 '12 at 18:58
  • i would consider this memoization, with the private variables being your lookup table, but it's just semantics :P – jbabey May 11 '12 at 19:01
  • @jbabey no, it's not semantics. Memoization is _specifically_ the automatic caching of the result of a _deterministic_ function given a specified input, such that subsequent calls to the same function with the same input retrieve the value from the cache instead of recalculating it. – Alnitak May 11 '12 at 19:05
9
function getClockTime(){
   var now    = new Date();
   var hour   = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour + ':' + minute + ':' + second + " " + ap;
   return timeString;
}

This Function will give the perfect time format in 1-12 hours

Baraskar Sandeep
  • 698
  • 2
  • 8
  • 16
  • 1
    Why are you formatting the minutes and the seconds? I think is not necessary. – mejiamanuel57 Apr 29 '14 at 14:09
  • Just a follow up - the formatting of minutes and seconds is necessary because JS getMinutes and getSeconds will return a single integer for the time. As opposed to 05, it will return 5. – Chris Timberlake Feb 03 '18 at 01:12
5

Shortest:

const hours12 = date => (date.getHours() % 12  || 12);

If you need padding with 0:

const hours12 = date => ("0"+(date.getHours() % 12  || 12)).slice(-2);

Another option, also with AM & PM:

const hours12 = date => date.toLocaleString('en-US', { hour: 'numeric', hour12: true })
chickens
  • 19,976
  • 6
  • 58
  • 55
3

Other answers are indeed very good. But I think, following can be included too.

var d = new Date();
var hour = d.getHours(); 
var minute = d.getMinutes();
var fulltime = "";

// create a 24 elements(0-23) array containing following values
const arrayHrs = [12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11];

    // since getMinutes() returns 0 to 9 for upto 9 minutes, not 00 to 09, we can do this
    if(minute < 10) {
        minute = "0" + minute;
    }

    if( hour < 12) {
        // Just for an example, if hour = 11 and minute = 29
        fulltime = arrayHrs[hour] + ":" + minute + " AM"; // fulltime = 11:29 AM
    }
    else {
        // similarly, if hour = 22 and minute = 8
        fulltime = arrayHrs[hour] + ":" + minute + " PM"; // fulltime = 10:08 PM
    }

See what I did there in arrayHrs ;)

falero80s
  • 368
  • 6
  • 12
1

the easy way to use this.

setInterval(function() {

var d = new Date();

document.getElementById("demo").innerHTML = 
d.getHours() % 12+" : "+d.getMinutes()+" : "+d.getSeconds();

}, 1000);
<p id="demo" ></p>
mahde amar
  • 11
  • 1
0
getDateTime = () => {
    const today = new Date();
    const day = today.toLocaleDateString('en-us', { weekday: 'short' });
    const month = today.toLocaleString('en-us', { month: 'short' });
    const date = today.getDate()
    const year = today.getFullYear()
    const hours = today.getHours()
    const minutes = today.getMinutes().toString()
    var dayORnight = "AM";
    if (hours > 11) { dayORnight = "PM"; }
    if (hours > 12) { hours = hours - 12; }
    if (hours == 0) { hours = 12; }
    if (hours < 10) { hours = "0" + hours; }
    if (minutes < 10) { minutes = "0" + minutes; }

    const datetime = `${day}, ${month} ${date}, ${year} at ${hours}:${minutes} ${dayORnight}`;
    console.log(datetime)
}
0

An answer similar to the accepted, but without the || operator.

Purely arithmetical:

// returns the hours number for a date, between 1 and 12
function hours12(date) { return (date.getHours() + 11) % 12 + 1; }

Test it here. Simulating hours 0 - 23:

var demoTable = document.getElementById("demo");

// simulate getHours() values 0-23
for (i = 0; i < 24; i++) {
  var row = demoTable.insertRow(-1);
  var format24Cell = row.insertCell(0);
  var conversionCell = row.insertCell(1);
  var format12Cell = row.insertCell(2);
  format24Cell.innerHTML = i;
  conversionCell.innerHTML = "( <b>" + i + "</b> + 11) % 12 + 1 =";
  
  // conversion takes place here
  format12Cell.innerHTML = (i + 11) % 12 + 1;
}
table {
  border-collapse: collapse;
  width: 100%;
}

table,
th,
td {
  border: 1px solid black;
}

th {
  padding: 0, 5px
}

td {
  padding-left: 5px;
}
<table id="demo">
  <tr>
    <th colspan="3">24 to 12 Hour Format Conversion Demo</th>
  <tr>
  <tr>
    <th>24 Hour Format</th>
    <th>Conversion</th>
    <th>12 Hour Format</th>
  </tr>
</table>
William Herrmann
  • 343
  • 2
  • 10
0

This converts 24h Time to 12h, and also add AM, and PM suffix too.

const hours12 = (date) => {
    let ampm = date.getHours() >= 12 ? 'pm' : 'am';
    return `${(date.getHours() % 12  || 12)} ${ampm}`;
};
console.log(hours12(new Date()));

modified version of @chickens.

Don Dilanga
  • 2,722
  • 1
  • 18
  • 20
0

This can be easily achieved using the .getHours() function. Remember that getHours returns integer values between 0 and 23 and so all you have to do is check for the 0 value

let date = new Date()
let hour = (date.getHours()===0)? 24:date.getHours()
Wise
  • 41
  • 1
  • 2