【问题标题】:new Date('december 2019') is not working in react js [duplicate]新日期('2019 年 12 月')在反应 js 中不起作用 [重复]
【发布时间】:2020-01-27 12:49:17
【问题描述】:

我想比较两个日期并正在使用

新日期('2019 年 12 月')

它在 react js / react native 中不起作用

        var resultList = [];
        var dated = new Date('december 2019');
        var endDated = new Date('march 2020');
        var monthNameList = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

        while (dated <= endDated)
        {
            console.log('checking');
            var stringDate = monthNameList[dated.getMonth()] + " " + dated.getFullYear() + " Qist is " + this.state.qistprice;
            resultList.push(stringDate);
            dated.setMonth(dated.getMonth()+1);
        }

在 vanilla javascript 中它工作正常。但是在本机反应中,如果我尝试使用这样的格式,它就不起作用了

新日期('2019 年 12 月 13 日') 那么它会起作用,但我不想让“2019 年 12 月”起作用.. 有什么办法吗?

我在 vanilla js 中尝试过的代码是这样的

var resultList = [];
    var dated = new Date('december 2019');
    var endDated = new Date('march 2020');
    var monthNameList = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    while (dated <= endDated)
    {
      console.log('checking');
      var stringDate = monthNameList[dated.getMonth()] + " " + dated.getFullYear() ;
      resultList.push(stringDate);
      dated.setMonth(dated.getMonth()+1);
    }
    console.log(resultList)

【问题讨论】:

  • “2019 年 12 月”应该是什么日期Date 对象是特定于第二个...!
  • 你为什么不直接使用new Date('december 01, 2019')?一样的
  • @SebastianKaczmarek 因为它同样不标准?
  • @VLAZ 我知道,这是另一种情况。但是OP要求别的东西。我不知道他的原因,也不知道他的工作。也许这就是它必须的样子?谁知道? new Date('december 01, 2019') 的结果是一样的
  • @samairali 您仍然需要定义 哪一天 您希望将 12 月的哪一天用于您的日期对象。如果没关系,只需在输入语法中添加硬编码的“01”即可使用第一个。

标签: javascript reactjs react-native


【解决方案1】:

您可以使用 moment.js 库。

moment('december 2019').format('L')
"12/01/2019"

【讨论】:

  • 添加额外的库并不是所有问题的解决方案...
  • new Date() 也在工作。
  • @AnkitKumarRajpoot 基本上是问题,我想了解的问题是它在 vanila js 中运行良好......它仅在 react js/native 中无法运行
  • 等等,我正在测试。
  • 你可以去这里测试...jsbin.com/micodudose/edit?html,console
【解决方案2】:

根据我的经验,您应该使用 momentjs (https://momentjs.com/) 库来操作和处理应用程序中的 Date。 Native Date() 对象真的很难管理,而且我也遇到了问题。

我现在无法用原生 Date 帮助你,但为了简短的回答,我建议使用 momentjs。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    相关资源
    最近更新 更多