简体   繁体   中英

How to convert a Date object to output only hh:mm am/pm

I am attempting to convert the following into a 12 hour am/pm format.

Currently I am recieving the Day, Month, Year and timezone.

Fixed by adding .toLocaleTimeString().replace(/([\\d]+:[\\d]{2})(:[\\d]{2})(. )/, "$1$3")*

<div id="time1"></div>
<div id="time2"></div>
var date = new Date('08/16/2019 12:00:00 PM UTC').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
document.getElementById("time1").innerHTML = date;

var date = new Date('08/16/2019 6:00:00 am UTC').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
document.getElementById("time2").innerHTML = date;

Basically what you have to do is use the Date() default javascript function and make sure you append the UTC timezone:

var date = new Date('08/16/2019 7:00:00 PM UTC')

date.toString=() //will then print out the timezone adjusted time

"Fri Aug 16 2019 22:00:00 GMT+0300 (Eastern European Summer Time)"

There are many built in javascript methods to handle converting date objects. This example will look to the browser to determine date format and time.

let time = Date.now();
time.toLocaleDateString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM