简体   繁体   中英

Javascript get year month date and time in custom format

In Javascript I want to get the current data and time in a custom format like this. "2016-01-01T05:06:07" . Can someone tell me how to get the current year-month-date-time in this format with quickest solution? As you can see I have trailing zeros with month, dates, hours, minutes and seconds so I want exactly like that. Any help and suggestions will be really appreciable. Thanks

The toISOString method provides the format you wish, but since it uses UTC you'll need to adjust the time for the local offset and trim the ends to remove the time zone and decimal seconds:

 function toLocalISOString(date) { var d = new Date(+date); d.setMinutes(d.getMinutes() - d.getTimezoneOffset()); return d.toISOString().replace(/(\\.\\d+)|(z$)/gi,''); } document.write(toLocalISOString(new Date()));

It could be added as a method to Date.prototype . I don't know how it will go over daylight saving boundaries, you should test thoroughly.

A polyfill for toISOString is available on MDN if required.

That looks like ISO

 var date = (new Date()).toISOString(); document.write('<pre>' + date + '</pre>'); date = date.substring(0, 19); document.write('<pre>' + date + '</pre>');

The Z is for the timezone, you can remove it by substring, like the fractions of seconds just before the Z.

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