【问题标题】:How to parse out date from non standard date string如何从非标准日期字符串中解析出日期
【发布时间】:2017-06-06 14:44:00
【问题描述】:

我有一个从 moment.js 以这种字符串格式返回的日期,用于日历应用程序。

2017 年 6 月 16 日星期五 00:00:00 GMT-0500(中部夏令时间)

如何将此字符串解析回“2017-06-16”,使用时刻回溯指定这是一个无效输入。使用它作为 new Date() 的实例返回给我一个不正确的日期。

var check = moment('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)', 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);
//-->invalid date

http://jsfiddle.net/t89apndd/

【问题讨论】:

  • 检查moment.js:momentjs.com/guides/#/parsing
  • 该控制台输出不显示字符串。它显示了一个名为 date 的对象属性,其值为 Moment 对象。看起来 _d 属性是一个 Date 对象(呈现为“Fri Jun ...”,因此您可以阅读它,用于调试目的)。如果它是一个字符串,它将显示在引号中。
  • @JordanRunning 完全同意你的观点,OP 正在记录一个时刻对象。 _d 是内部使用的私有财产,不应使用。 Moment 有format() 方法来显示时刻对象的字符串值。

标签: javascript date momentjs


【解决方案1】:

完全同意Jordan Running的评论

该控制台输出不显示字符串。它显示了一个名为 date 的对象属性,其值为 Moment 对象

由于您已经有一个矩对象(您的date var),您可以简单地使用format() 以您喜欢的格式显示矩值。

你可以这样做:

date.format('YYYY-MM-DD');

这是一个现场样本:

var date = moment([2017, 5, 16]);
console.log(date); // Print moment object (like the one provided in the question)
console.log(date.format('YYYY-MM-DD')); // Print string output of format (in the desired format)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

【讨论】:

    【解决方案2】:

    与您的日期转储相反,对象显示属性

    _isValid: false
    

    检查小提琴和控制台日志 https://jsfiddle.net/s6x87u1p/

    【讨论】:

      【解决方案3】:

      你不需要moment.js

      只需使用原生的Date() 构造函数。

      const date = new Date('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)');
      const day = date.getDate();
      const month = date.getMonth() + 1;
      const year = date.getFullYear();
      console.log(day, month, year);

      如果您需要转换现有的 moment.js 日期:

      const momentDate = ...;//insert your moment.js date here
      const date = new Date(momentDate._i);
      const day = date.getDate();
      const month = date.getMonth();
      const year = date.getFullYear();
      console.log(day, month, year);

      【讨论】:

      • "如果您需要转换现有的 moment.js 日期..." 嗯?既然可以使用 Moment 的内置 toDate 方法,为什么还要访问“私有”属性 (_i)?
      【解决方案4】:

      如果你真的想要moment.js...

      var check = moment(new Date('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)'));
      
      var month = check.format('M');
      var day   = check.format('D');
      var year  = check.format('YYYY');
      
      console.log(month, day, year);
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

      【讨论】:

        猜你喜欢
        • 2013-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多