简体   繁体   English

在没有浏览器进行与时区相关的任何调整的情况下,在 JavaScript 中写入日期的正确方法是什么

[英]What is the correct way to write a Date in JavaScript without having browsers do any adjustments related to timezone

I'm not in the GMT timezone and new Date('1995-02-22') gives me我不在 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)

I'm coding something related to a birthday, so the year month and day are super important, but the time isn't.我正在编写与生日相关的代码,所以年月日非常重要,但时间不是。 What is the proper way to handle this?处理这个问题的正确方法是什么? Using moment.js seems beyond overkill.使用 moment.js 似乎太过分了。

Choose one: either create a Date with the correct date in UTC time, or with the correct date in the local timezone.选择一个:使用 UTC 时间中的正确日期创建日期,或者使用本地时区中的正确日期创建日期。 If the timestamp might be used by other clients too, use UTC time for easy compatibility.如果时间戳也可能被其他客户端使用,请使用 UTC 时间以便于兼容。

If you create the Date with the correct UTC time, then just use the get* UTC methods to retrieve the year/month/day.如果您使用正确的 UTC 时间创建日期,则只需使用 get* UTC 方法来检索年/月/日。

 const date = new Date('1995-02-22'); console.log( date.getUTCFullYear(), (date.getUTCMonth() + 1), // 0 indexed date.getUTCDate(), );

Or create the Date in local time and use the local versions of the above, like .getFullYear .或者在本地时间创建日期并使用上述本地版本,例如.getFullYear

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

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