简体   繁体   中英

Moment.js - I'm parsing date but it still complains

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]

As far as I can tell, I am parsing the date according to the parse docs.

Any suggestions?

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;
}

尝试格式 - 'MD-YYYY',因为月份和日期是单个数字,并且您不是前缀0。

The problem in your code is that refDate becomes: '9-4-2016' and that is not a known format. Hence the call to .calendar() throws that error.

So, I would recommend changing your code to:

function dateToMDY(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + (m <= 9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d) + '-' + y; 
}

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 = dateToMDY(today);
  var graphTitle = moment(data.date, 'MM-DD-YYYY').calendar(refDate, formats);
  return graphTitle;
}

When you call calendar, it will accept a moment object for refDate. Since the moment you appear to want is simply one month from today, your code can be written as follows:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM