且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

moment.js 上的无效日期

更新时间:2023-01-31 14:54:29

你必须使用 moment(String, String) 代替 moment(String) 因为您的输入既不是 ISO 8601 也不是 RFC 2822 格式.

You have to use moment(String, String) intead of moment(String) since your input is neither in ISO 8601 nor RFC 2822 format.

从字符串创建时刻时,我们首先检查该字符串是否与已知的 ISO 8601 匹配 格式,然后我们检查字符串是否与 RFC 2822 日期时间 格式匹配如果未找到已知格式,则在回退到 new Date(string) 之前.

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.

警告:浏览器对解析字符串的支持不一致.由于没有规定应该支持哪些格式,因此在某些浏览器中有效的方法在其他浏览器中无效.

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

对于解析除 ISO 8601 字符串以外的任何内容的一致结果,您应该使用 String +格式.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

这是一个现场示例:

var data = '31/12/2012'
console.log( moment(data, 'DD/MM/YYYY').format('ll') );

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>