[英]What is the correct way to write a Date in JavaScript without having browsers do any adjustments related to timezone
我不在 GMT 时区和new Date('1995-02-22')
给我
new Date('1995-02-22') <-- Enter this in the console
Tue Feb 21 1995 16:00:00 GMT-0800 (Pacific Standard Time)
我正在编写与生日相关的代码,所以年月日非常重要,但时间不是。 处理这个问题的正确方法是什么? 使用 moment.js 似乎太过分了。
选择一个:使用 UTC 时间中的正确日期创建日期,或者使用本地时区中的正确日期创建日期。 如果时间戳也可能被其他客户端使用,请使用 UTC 时间以便于兼容。
如果您使用正确的 UTC 时间创建日期,则只需使用 get* UTC 方法来检索年/月/日。
const date = new Date('1995-02-22'); console.log( date.getUTCFullYear(), (date.getUTCMonth() + 1), // 0 indexed date.getUTCDate(), );
或者在本地时间创建日期并使用上述本地版本,例如.getFullYear
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.