这个问题与this question有关.
因此,如果我们使用如下 ISO 字符串构造日期:
new Date("2000-01-01")
根据我们所在的时区,我们可能会得到不同的年份和日期。
我需要能够在 Javascript 中构造日期,该日期始终在字符串中指示正确的 year
、day
和 month
像 2000-01-01
,如果我们像这样使用反斜杠,则基于其中一个问题的答案:
const d = new Date("2000/01/01")
然后当使用相应的日期 API 方法时,我们将始终获得正确的 year
、day
和 month
:
d2.getDate();
d2.getDay();
d2.getMonth();
d2.getFullYear();
所以我只是想验证一下我的理解是否正确?
最终我需要能够像这样创建 Date
实例,例如:
const d3 = new Date('2010/01/01');
d3.setHours(0, 0, 0, 0);
并且时间部分应始终为零,年
、月
和日
应为字符串中指定的数字。
想法?
我刚刚做了一个快速测试: https://stackblitz.com/edit/typescript-eztrai
const date = new Date('2000/01/01');
console.log(`The day is ${date.getDate()}`);
const date1 = new Date('2000-01-01');
console.log(`The day is ${date1.getDate()}`);
它记录了这个:
The day is 1
The day is 31
所以看起来使用反斜杠应该可行......
或者可能像这样使用年、月(基于 0 的索引)和日构造函数值:
const date3 = new Date(2000, 0, 1);
date3.setHours(0, 0, 0, 0);
console.log(`The day is ${date3.getDate()}`);
console.log(`The date string is ${date3.toDateString()}`);
console.log(`The ISO string is ${date3.toISOString()}`);
console.log(`Get month ${date3.getMonth()} `);
console.log(`Get year ${date3.getFullYear()} `);
console.log(`Get day ${date3.getDate()} `);
注意
Runar 在已接受的答案评论中提到了一些非常重要的事情。要在使用 Javascript 日期 API 时获得一致的结果,请使用 getUTCDate()
等方法。如果日期字符串是 2000-01-01
,这将为我们提供 1
。 getDate()
方法可以给我们一个不同的数字...
最佳答案
来自 Date.parse
method 的 ECMA 标准:
When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
发生的事情是 New Date()
隐式调用字符串上的 Date.parse
。 "2000-01-01"
版本符合 Date Time String Format缺少偏移表示,因此假定您指的是 UTC。
当您使用 "2000/01/01"
作为输入时,标准是这样说的:
If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
所以简而言之,浏览器可以做他们想做的事。在您的情况下,它假定您指的是本地时间的偏移量,因此当您转换为 UTC 时,无论您位于哪个偏移量,都会被添加。
为了获得一致的结果,也许您想看看 Date.UTC
new Date(Date.UTC(2000, 0, 1))
如果您需要传入 ISO 字符串,请确保包含 +00:00
的时间偏移(通常缩写为 z
)
new Date("2000-01-01T00:00:00Z");
如果您想稍后将日期设置为不同的日期,使用等效的 UTC setter 方法(例如 setUTCHours
)。
当您检索日期时,还要确保使用 UTC getter 方法(例如 getUTCMonth
)。
const date = new Date("2000-01-01T00:00:00Z");
console.log(date.getUTCDate());
console.log(date.getUTCMonth());
console.log(date.getUTCFullYear());
如果您想以特定格式检索日期,您可以查看 Intl.DatTimeFormat
, 请记住将 timeZone: "UTC"
传递给 options .
const date = new Date("2000-01-01T00:00:00Z");
const dateTimeFormat =
new Intl.DateTimeFormat("en-GB", { timeZone: "UTC" });
console.log(dateTimeFormat.format(date));
关于javascript - 在 Javascript 中创建与时区无关的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70481329/