简体   繁体   English

Javascript 日期格式今天亚洲 GMT+8

[英]Javascript date format today Asia GMT+8

In my country, today is 12/15/2022 , I'm from Asia which is gmt+8.在我的国家,今天是12/15/2022年 12 月 15 日,我来自亚洲,即 gmt+8。

Basically I want my date to be 2022-12-15T00:00:00.000Z instead of showing 2022-12-14T16:00:00.000Z.基本上我希望我的日期是2022-12-15T00:00:00.000Z而不是显示2022-12-14T16:00:00.000Z.

here is the code:这是代码:

 const today = new Date().toLocaleDateString(); console.log(new Date(today));

But I really want it to be exact like this但我真的希望它完全像这样

2022-12-15T00:00:00.000Z

is it possible without using logic "add +8 hours"?是否可以不使用逻辑“添加 +8 小时”?

you can force your time zone like this你可以像这样强制你的时区

console.log(new Date(new Date().toLocaleDateString('en', {timeZone: 'Asia/Hong_Kong'})))

Edit: changed toLocaleString to toLocaleDateString this should meet your needs now编辑:将 toLocaleString 更改为 toLocaleDateString 这现在应该可以满足您的需求

One way is to run your code in UTC zone so that you don't accidentally create dates in different time zones.一种方法是在 UTC 时区运行您的代码,这样您就不会意外地在不同时区创建日期。 You can set TZ='UTC' environment variable for this.您可以为此设置TZ='UTC'环境变量。

Otherwise you can create the date like this.否则你可以像这样创建日期。

const today = new Date().setUTCHours(0, 0, 0, 0); // note 'today' is a number now
> console.log(new Date(today))
2022-12-15T00:00:00.000Z

You can first convert the date to a local date string, then parse the year, month and day from it to construct the local ISO zero date string:您可以先将日期转换为本地日期字符串,然后从中解析年月日以构造本地 ISO 零日期字符串:

 const localDate = new Date().toLocaleDateString('en', {timeZone: 'Asia/Hong_Kong'}); console.log('localDate:', localDate); let m = localDate.match(/(\d+)\/(\d+)\/(\d+)/); let localZero = m[3] + '-' + m[1] + '-' + m[2] + 'T00:00:00.000Z'; console.log('localZero:', localZero);

Output:输出:

localDate: 12/15/2022
localZero: 2022-12-15T00:00:00.000Z

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

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