gpt4 book ai didi

javascript - 将字符串日期转换为不带时区的 ISO 格式

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

我的输入日期格式类似于2018年4月1日。我需要将其转换为 2018-04-01 格式。当我使用以下代码时:

var dateinput = new Date('2 April 2018').toISOString();
alert(dateinput);

我得到的结果是:

2015-04-01 T18:30:00.000Z

比我输入的时间少了 1 天。另外,如何从日期函数中删除部分 T18:30:00.000Z

最佳答案

您遇到的问题是由于在构建新的 Date 实例时在幕后使用 Date.parse() 造成的。这实际上是不推荐的,如 MDN page for Date 中所述。 :

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.

如果您的输入格式足够简单(即始终是天数,然后是月份,然后是年份,并且具有有效值),那么您最好的选择可能是创建一个函数来解析您的输入字符串并构建 Date 使用 Date.UTC()setUTC*() 函数的对象。编写另一个函数,该函数接受 Date 对象并使用 getUTC*() 方法以目标格式构建字符串。这样您就可以确保您的约会不会错过,也不会受到时区的困扰。

如果您的用例实际上比这更复杂(多种输入和输出格式),那么最好考虑使用像 moment.js 这样的库。 .

关于javascript - 将字符串日期转换为不带时区的 ISO 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49486416/

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