Moment.js - 我正在解析日期,但它仍然抱怨

时间:2016-09-04 05:35:33

标签: javascript momentjs

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info. Arguments: [object Object]

据我所知,我正在根据解析文档解析日期。

有什么建议吗?

function graphTitleGenerator(data) {
  var formats = {
    sameDay: '[Today]',
    nextDay: '[Tomorrow]',
    nextWeek: 'dddd',
    lastDay: '[Yesterday]',
    lastWeek: 'MM/DD/YYYY',
    sameElse: 'MM/DD/YYYY'
  }
  var today = new Date();
  var refDate =  (today.getMonth()+1) + '-' + today.getDate()
    + '-' + today.getFullYear();
  var graphTitle = moment(data.date, 'MM-DD-YYYY').calendar(refDate, formats);
  return graphTitle;
}

3 个答案:

答案 0 :(得分:1)

请尝试使用格式 - 'M-D-YYYY',因为月份和日期是个位数而您不是前缀为0.

答案 1 :(得分:1)

您的代码中的问题是<div id="logoup" class="logoup">DEEP</div> <button id='btn'>CLICK</button> 变为:refDate并且这不是已知格式。因此,对'9-4-2016'的调用会抛出该错误。

因此,我建议您将代码更改为:

.calendar()

答案 2 :(得分:1)

当您调用日历时,它将接受refDate的时刻对象。从您想要的那一刻开始,只需一个月,您的代码可以写成如下:

function graphTitleGenerator(data) {
  var formats = { 
    sameDay: '[Today]',
    nextDay: '[Tomorrow]',
    nextWeek: 'dddd',
    lastDay: '[Yesterday]',
    lastWeek: 'MM/DD/YYYY',
    sameElse: 'MM/DD/YYYY'
  }

  var graphTitle = moment(data.date, 'MM-DD-YYYY').calendar(moment().add(1, month), formats);
  return graphTitle;
}