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!
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.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.
You can convert the current time to 12 hour format with a one liner
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' });
This should work.