How to get current time in a format hh:mm AM/PM in Javascript?

后端 未结 4 1352
小鲜肉
小鲜肉 2021-01-05 11:26

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

4条回答
  •  天涯浪人
    2021-01-05 11:57

    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' });

提交回复
热议问题