【问题标题】:How can I get moment.js to treat the date '1234 56 78' as an invalid date?如何让 moment.js 将日期“1234 56 78”视为无效日期?
【发布时间】:2018-01-30 20:33:48
【问题描述】:

我有一个 Javascript/NodeJS 单元测试,它试图验证无效日期是否引发异常。代码是这样的:

let inputDate = '1234 56 78';
let useFormat = 'DD MMM YYYY';
try {
    let aDate = moment(inputDate, useFormat);
    if (isNaN(aDate)){
        throw Error("Invalid date: " + inputDate)
    }
    console.log('date [' + inputDate + '] is valid and parses to [' + aDate.format(useFormat) + ']');

} catch (ex) {
    // success
    console.log('got ex',ex.toString())
}

控制台输出为:

date [1234 56 78] is valid and parses to 12 Jan 1978

您可以在 jsbin.com 中轻松运行它来重现错误,抱歉我没有指向它的链接。

我需要怎么做才能将其视为无效日期?

或者,我需要了解什么才能了解日期有效。 :-)

【问题讨论】:

    标签: javascript node.js momentjs


    【解决方案1】:

    strict mode 中运行 Moment.js 将拒绝输入:

    let aDate = moment(inputDate, useFormat, true);
    

    【讨论】:

      猜你喜欢
      • 2014-02-27
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      相关资源
      最近更新 更多