[英]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. 您的代码中的问题是refDate
变为: '9-4-2016'
并且这不是已知的格式。 Hence the call to .calendar()
throws that error. 因此,对.calendar()
的调用会抛出该错误。
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. 当您调用日历时,它将接受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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.