【问题标题】:momentjs isValid is returning false when it should be true and visa versamomentjs isValid 在应该为真时返回假,反之亦然
【发布时间】:2019-05-04 11:33:13
【问题描述】:

使用 HTML、javascript 和 jQuery 我正在使用“xlsx.full.min.js”从 MS excel 导入日期。我已将 MS Excel 中的日期字段设置为文本,因此 MS Excel 在导出时不会更改其格式。导入后,我会解析创建的表以验证每个字段。要验证我使用的日期字段:

var dateFormat = 'DD/MM/YYYY';
alert("$(this).text(): " + $(this).text());
alert(moment(moment($(this).text()).format(dateFormat),dateFormat,true).isValid());

当 MS Excel 日期字段包含“13/12/2018”时,返回 false。当 MS Excel 日期字段包含“12/13/2018”时,返回 true。这两个值都显示在警报中,因此我知道它们被正确传递了。

由于我已将日期格式设置为“DD/MM/YYYY”,为什么该格式会失败而“MM/DD/YYYY”会通过?

【问题讨论】:

    标签: javascript jquery html excel momentjs


    【解决方案1】:

    MomentJS 在对其执行操作之前将日期从字符串转换为其对象。如果未指定格式,则采用默认格式。解析操作在这里解释:https://momentjs.com/docs/#/parsing/string/

    因此,在您的情况下,您必须在创建时刻对象时传递日期格式。像这样:

    var dateFormat = "DD/MM/YYYY";
    moment("12/13/2018",dateFormat).isValid() //will return false
    moment("13/12/2018",dateFormat).isValid() //will return true
    

    更新:

    MomentJS 允许解析日期,即使指定的日期包含除格式之外的其他字符。例如,“1A/2B/2018”将被视为“1/2/2018”的有效日期。

    为了避免这种情况,并检查格式和日期是否完全匹配,moment 对象应传递一个额外的布尔值以启用严格模式。

    moment("1A/2B/2018", dateFormat).isValid() //will return true
    moment("1A/2B/2018", dateFormat, true).isValid() //will return false
    

    【讨论】:

    • 在进一步测试中,使用 moment($(this).text(),dateFormat).isValid() 将“R2C5”作为有效日期返回
    • 嗨。我用“R2C5”被视为有效日期的原因更新了答案。在严格模式下创建时刻对象以避免这种情况。
    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多