为了理解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>
有人能给我解释一下吗??
发布于 2018-05-22 01:21:51
当您传递字符串时,moment会检查它是否是有效的日期格式,如果不是,它将返回到内置的javascript Date.parse()方法。
moment.js文档说:
从字符串创建时刻时,我们首先检查字符串是否与已知的ISO8601格式匹配,然后检查字符串是否与RFC2822日期时间格式匹配,如果未找到已知格式,则返回到新日期(字符串)的回退。
在遇到10之前,Date.parse不会识别字符串中任何有用的内容;它会丢弃其余的内容。假定使用默认的日期格式,具体取决于您所在的位置和语言。在我自己的例子中,在美国,格式是MM/DD。结果是字符串被解析为10月1日的日期(10月1日,没有指定的日期默认为1日)。然后(我怀疑是因为千年虫的原因)它假设是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 .来结束字符串,如果您将相同的行为(invalid date)传递给内置的Date方法,您将注意到相同的行为。
https://stackoverflow.com/questions/50452526
复制相似问题