moment.js 上的无效日期 [英] Invalid Date on moment.js

查看:154
本文介绍了moment.js 上的无效日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 moment JS 格式化日期时无效的日期

当我试图将这个日期格式化为 31/12/2012moment(data).format('ll') 时,我得到了无效的日期,我得到了一个无效的日期返回.

I got invalid date when I tried to format this date 31/12/2012to moment(data).format('ll') and i get a invalid date return.

推荐答案

你必须使用 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>

这篇关于moment.js 上的无效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆