[英]How to parse a moment.js date object
I am looking to diff the duration in months and days for 2 dates. 我想以2个月的天数和天数来比较持续时间。 I having trouble accessing the properties of the object I get back from moment.js.
我无法访问从moment.js返回的对象的属性。
I can't seem to access the properties of the Duration._data object. 我似乎无法访问Duration._data对象的属性。
var x = moment(); //todays date
var y = moment("2015-12-1"); // an earlier date
var duration = moment.duration(x.diff(y));
console.log("diff: ", duration);
returns: 返回:
diff:
Duration {_isValid: true, _milliseconds: 106742243043, _days: 0, _months: 0, _data: {…}, …}
_data:
days: 17
hours: 10
milliseconds: 43
minutes: 37
months: 4
seconds: 23
years: 3
Was hoping to get the months and days props, using duration._data.days for example. 希望通过使用duration._data.days来获取months and days道具。 But I get the error message:
但是我收到错误消息:
Property '_data' does not exist on type 'Duration' 类型“ Duration”上不存在属性“ _data”
Use the range
, Luke: 使用
range
,卢克:
var x = moment(); //todays date
var y = moment("2015-12-1"); // an earlier date
var duration = moment.duration(x.diff(y));
const range = moment.range(y, x);
const days = range.diff('days');
console.log("diff: ", days); // gives the number of days
You can simply use duration setter like months()
, days()
etc 您可以简单地使用工期设置器,例如
months()
, days()
等
Here a live sample: 这是一个现场样本:
var x = moment(); //todays date var y = moment("2015-12-1", 'YYYY-M-D'); // an earlier date var duration = moment.duration(x.diff(y)); console.log("diff: ", duration.months(), duration.days());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
If you want to add the format()
method to duration have a look at moment-duration-format plug-in. 如果要向持续时间添加
format()
方法,请查看一下矩持续时间格式插件。
var a = moment(); //todays date
var b = moment("2015-12-1"); // an earlier date
var years = a.diff(b, 'year');
b.add(years, 'years');
var months = a.diff(b, 'months');
b.add(months, 'months');
var days = a.diff(b, 'days');
console.log(years + ' years ' + months + ' months ' + days + ' days');
I always use this function to get the the difference in dates. 我总是使用此功能来获取日期之间的差异。
const availableTime = moment(endDate);
const timeDifference = availableTime.diff(moment(startDate));
return moment.duration(timeDifference);
You can then: 然后,您可以:
duration.days()
duration.minutes()
Etc.. 等等..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.