gpt4 book ai didi

javascript - 将数字转换为日期的时刻

转载 作者:行者123 更新时间:2023-11-29 23:21:27 26 4
gpt4 key购买 nike

为了了解 moment.js 如何将字符串转换为日期,我遇到了这个问题。

let date = "User has logged in to more than 10 .";
console.log(moment(date)); //output date

let invalid = "User has logged in to more than 10 a";
console.log(moment(invalid)); //output invalid date
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js
"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/2.2.0/moment-range.js"></script>

谁能给我解释一下??

CodePen link

最佳答案

当您传递字符串 moment 时,检查它是否是有效的日期格式,如果不是,它会回退到内置的 javascript Date.parse()方法。

moment.js 文档说:

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.

Date.parse 在遇到 10 之前无法识别字符串中的任何有用信息;它会掉落其余部分。假设使用默认日期格式,这取决于您的位置和语言。在我自己的例子中,在美国,格式是 MM/DD。结果是字符串被解析为 10 月 1 日的日期(第 10 个月,没有指定的日期默认为 1 日)。然后(我怀疑是出于 Y2K 的原因)假设是 2001 年,因为没有给出年份。

我们从 javascript 的内置 Date 方法中得到相同的行为:

new Date(Date.parse('User has logged in to more than 10.'))
// Mon Oct 01 2001 00:00:00 GMT-0400 (EDT) <- As printed from Michigan.

在第二种情况下,您尝试以 10 a 而不是 10 结束字符串。 您会注意到相同的行为(无效日期) 如果您将其传递给内置的 Date 方法。

关于javascript - 将数字转换为日期的时刻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452526/

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