【问题标题】:Moment format returning 'invalid date'时刻格式返回“无效日期”
【发布时间】:2021-11-02 14:35:21
【问题描述】:

我有以下几点:

const input: string = '2021-11-2T10:20:00+01:00';

const date: string = moment( input ).format('YYYY-MM-DD');
const time: string = moment( input ).format('HH:mm');

请有人告诉我为什么“日期”和“时间”都返回“无效日期”?

据我了解,“输入”字符串是标准日期格式(moment 给了我这种格式)。

【问题讨论】:

  • 我在momentjs.com 上将此代码粘贴到我的控制台中,但没有收到此错误。我刚得到这个:Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
  • 嗯。我刚刚做了moment().format(); 并使用返回的这个值作为“输入”值,它可以工作。我想我使用的日期有问题。
  • 让我推荐 luxon 库。如果时刻应该关键地打破,那是一个很好的选择。

标签: javascript typescript momentjs


【解决方案1】:

注意前导零(RFC2822/ISO 格式要求)。您可以使用Date 构造函数验证日期字符串:

new Date('2021-11-2T10:20:00+01:00') // Invalid Date (because of date = '2' instead of '02')
new Date('2021-11-02T10:20:00+01:00') // Tue Nov 02 2021 11:20:00 GMT+020 (works fine!)

moment 实例相同:

moment('2021-11-2T10:20:00+01:00') // invalid (error or deprecation warning depends on 'moment' version)
moment('2021-11-02T10:20:00+01:00') // valid

更新:article about standarts with useful links

【讨论】:

    【解决方案2】:

    您使用的是时间戳记。有一个错误。所以 timestamptz 的格式如下:

    YYYY-MM-DDThh:mm:ssZZ
    

    你一天中少了一个“0”:

    2021-11-02T10:20:00+01:00

    那么你可以这样做:

    const fullDate = moment('2021-11-02T10:20:00+01:00')
    const date = moment( input ).format('YYYY-MM-DD')
    const time = moment( input ).format('HH:mm')
    

    注意我删除了: string。你不需要定义打字顺便说一句。可以推断出来。

    【讨论】:

      【解决方案3】:

      我使用的输入字符串不知何故无效。当我使用“2021-11-02T14:43:59+00:00”时,它工作正常。

      【讨论】:

      • 是的,正如@Xeelley 解释的那样。您不需要发布第二个答案,您应该将他们的答案标记为已接受
      猜你喜欢
      • 2020-07-15
      • 2017-10-06
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      相关资源
      最近更新 更多