9

I have a Javascript in which I need to paste the current time in a format HH:MM AM/PM. There's one catch - I need to put the time that starts in two hours from now, so for example, instead of 7:23PM I need to put 9:23PM, etc.

I tried to do something like: var dateFormat = new Date("hh:mm a") but it didn't work. I also tried to use:

var today = new Date();
var time = today.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
alert(time);

but all I've seen was e.g. 18:23 instead of 6:23 PM (probably because of toLocaleTimeString() and my location in Europe) - maybe there's some unified way to do that that will work all around the World?. Also, I don't know exactly how to add the 2 hours to the final result. Can you help me? Thanks!

Ashesh
  • 3,499
  • 1
  • 27
  • 44
randomuser1
  • 2,733
  • 6
  • 32
  • 68
  • 1
    Just add 2 hours to the date object and format it then – Jonathan Apr 25 '15 at 16:39
  • Maybe these old posts will help: "How do you display javascript datetime in 12 hour AM/PM format?" --> http://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format or "How do you display javascript datetime in 12 hour AM/PM format?" --> http://stackoverflow.com/questions/24315100/convert-utc-time-to-hours-minutes-and-am-pm-format-in-javascript – nicolaus-hee Apr 25 '15 at 16:42
  • I would also reccomend moment.js, a reasonably small lib for manipulating and formatting Date objects. http://momentjs.com/ – Andrew Lavers Apr 25 '15 at 16:44
  • Does this answer your question? [How do you display JavaScript datetime in 12 hour AM/PM format?](https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format) – Tariqul Islam Dec 04 '19 at 18:46

4 Answers4

16

You can convert the current time to 12 hour format with a one liner

new Date().toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });

And to add two hours to your current time

Date.now() + 2 * 60 * 60 * 1000

So you can do it in a simple one line as:

new Date(Date.now() + 2 * 60 * 60 * 1000).toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });

acesmndr
  • 8,137
  • 3
  • 23
  • 28
6

Use Date methods to set and retrieve time and construct a time string, something along the lines of the snippet.

[edit] Just for fun: added a more generic approach, using 2 Date.prototype extensions.

var now = new Date();
now.setHours(now.getHours()+2);
var isPM = now.getHours() >= 12;
var isMidday = now.getHours() == 12;
var result = document.querySelector('#result');
var time = [now.getHours() - (isPM && !isMidday ? 12 : 0), 
            now.getMinutes(), 
            now.getSeconds() || '00'].join(':') +
           (isPM ? ' pm' : 'am');
            
result.innerHTML = 'the current time plus two hours = '+ time;

// a more generic approach: extend Date
Date.prototype.addTime = addTime;
Date.prototype.showTime = showTime;

result.innerHTML += '<h4>using Date.prototype extensions</h4>';
result.innerHTML += 'the current time plus twenty minutes = '+ 
                      new Date().addTime({minutes: 20}).showTime();
result.innerHTML += '<br>the current time plus one hour and twenty minutes = '+ 
                      new Date().addTime({hours: 1, minutes: 20}).showTime();
result.innerHTML += '<br>the current time <i>minus</i> two hours (format military) = '+ 
                      new Date().addTime({hours: -2}).showTime(true);
result.innerHTML += '<br>the current time plus ten minutes (format military) = '+ 
                      new Date().addTime({minutes: 10}).showTime(true);


function addTime(values) {
  for (var l in values) {
    var unit = l.substr(0,1).toUpperCase() + l.substr(1);
    this['set' + unit](this['get' + unit]() + values[l]);
  }
  return this;
}

function showTime(military) {
  var zeroPad = function () {
    return this < 10 ? '0' + this : this;
  };
  
  if (military) {
    return [ zeroPad.call(this.getHours()),
             zeroPad.call(this.getMinutes()),
             zeroPad.call(this.getSeconds()) ].join(':');
  }
  var isPM = this.getHours() >= 12;
  var isMidday = this.getHours() == 12;
  return time = [ zeroPad.call(this.getHours() - (isPM && !isMidday ? 12 : 0)),
                  zeroPad.call(this.getMinutes()),
                  zeroPad.call(this.getSeconds()) ].join(':') +
                (isPM ? ' pm' : ' am');

  
 
}
<div id="result"></div>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 1
    Nice! Don't know why most of the questions about time on here ask for the unreadable UNIX timestamp.... like who needs that in their project / app lol – Leon Gaban May 05 '15 at 14:54
3

Simply, you can do this


const date = new Date()
const options = {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
};
const time = new Intl.DateTimeFormat('en-US', options).format(date)
console.log(time)

For more details, you can refer to the MDN docs regarding the same.

cRAN
  • 195
  • 1
  • 2
  • 16
Naren
  • 4,152
  • 3
  • 17
  • 28
1

Note that the accepted answer, while good, does not appear to meet the format requirement of: HH:MM AM/PM. It returns midnight as "0:0:38am" and so forth.

There are many ways one could do this and one alternative is shown below. Click the "Run Code Snippet" to test.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Clock</title>
</head>
<body>
<span id="clock"  style="font-family: monospace; font-size: 48px; background-color: black; color: lime; padding: 10px;">00:00:00 AM</span>
<script type="text/javascript">

function getTime( ) {
 var d = new Date( ); 
 d.setHours( d.getHours() + 2 ); // offset from local time
 var h = (d.getHours() % 12) || 12; // show midnight & noon as 12
 return (
  ( h < 10 ? '0' : '') + h +
  ( d.getMinutes() < 10 ? ':0' : ':') + d.getMinutes() +
                // optional seconds display
  // ( d.getSeconds() < 10 ? ':0' : ':') + d.getSeconds() + 
  ( d.getHours() < 12 ? ' AM' : ' PM' )
 );
 
}

var clock = document.getElementById('clock');
setInterval( function() { clock.innerHTML = getTime(); }, 1000 );
</script>
</body>
</html>
Yogi
  • 6,241
  • 3
  • 24
  • 30