简体   繁体   English

Javascript以自定义格式获取年月日期和时间

[英]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.在 Javascript 中,我想以这样的自定义格式获取当前数据和时间。 "2016-01-01T05:06:07" . "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: toISOString方法提供您想要的格式,但由于它使用 UTC,您需要调整本地偏移的时间并修剪末端以删除时区和十进制秒:

 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 .它可以作为一个方法添加到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.如果需要,可以在 MDN 上找到toISOString 的 polyfill

That looks like ISO看起来像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. Z 用于时区,您可以通过子字符串删除它,例如 Z 之前的几分之一秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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