gpt4 book ai didi

javascript - 获取给定日期的一年中的最后一个日期

转载 作者:行者123 更新时间:2023-12-01 02:03:44 24 4
gpt4 key购买 nike

var reportDateStr = "2018-05-21";
var reportDate = new Date(reportDateStr);
var y = reportDate.getFullYear();
var lastDateOfReportYear = new Date(reportDate.getFullYear(), 11, 31);

console.log(lastDateOfReportYear)

我得到的不是 2018 年的最后一天,即 2018 年 12 月 31 日,而是 2019 年 1 月 31 日
请问您能告诉我上面的代码有什么问题以及为什么我得到的是 2019 年 1 月 31 日吗?

最佳答案

说实话,如果不深入了解您正在使用的浏览器/节点版本(我们稍后会明白为什么这很重要),我有点不确定为什么您会在一个月后约会(一月) 2019 年 1 月 1 日对于您遇到的问题更有意义),但我会对为什么 2019 年 1 月 1 日可能会发生提供更高层次的解释。

来自Date文档:

Note: Where Date is called as a constructor with more than one argument, the specified arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.

因此,因为您正在使用三个参数构造一个新日期,所以该日期代表您的本地时间。

const localDate = new Date(2018, 11, 31);
console.log({
localDate // in EST this will be "2018-12-31T05:00:00.000Z"
});

请注意,时间是“05”(针对美国东部时间),而不是“00”。按照建议使用 Date.UTC 会将其设置为“00”,无论本地时间如何。

const localDate = new Date(Date.UTC(2018, 11, 31));
console.log({
localDate // This will always be "2018-12-31T00:00:00.000Z"
});

从日期字符串创建日期时需要注意的其他一些事项(不推荐):

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

因此,由于不同的 JavaScript 实现,生成的日期可能会有所不同。看看这个chart供有关此问题的引用。

另请注意 getFullYear使用本地时间来获取全年值。这也会影响您所需的输出。

因此,为了更安全一点,您可以使用 UTC 进行所有计算:

const reportDateStr = '2018-05-21';
const reportDate = new Date(reportDateStr); // This could still be problematic
const y = reportDate.getUTCFullYear();
const lastDateOfReportYear = new Date(Date.UTC(y, 11, 31));
console.log(lastDateOfReportYear.toUTCString());

还有像 moment.js 这样的库这可以帮助解决处理时间和日期的众多问题。

关于javascript - 获取给定日期的一年中的最后一个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50293853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com