[英]How to get days with moment.js fromNow method
I'd like to get days from a date to now with momentjs.我想使用momentjs从日期到现在的天数。
I've tried with fromNow().我已经尝试过 fromNow()。 The method return value as string.
该方法以字符串形式返回值。
And its unit change depends on the length of range.它的单位变化取决于射程的长度。
var m = moment("2014-01-01"); // or whatever start date you have
var today = moment().startOf('day');
var days = Math.round(moment.duration(today - m).asDays());
Or if you prefer, the last line can be simplified:或者,如果您愿意,可以简化最后一行:
var days = Math.round((today - m) / 86400000);
Note that even though the start date was specified without a time (which assumes midnight), rounding is still necessary to get a whole number because of potential differences in UTC offset due to daylight saving time.请注意,即使指定的开始日期没有时间(假设为午夜),由于夏令时可能会导致 UTC 偏移量的潜在差异,因此仍然需要舍入以获取整数。
If you still want to use Moment to get the "In X days" or "X days ago" you can use moment.from(date) instead of moment.fromNow() and just remove all notion of times.如果您仍然想使用 Moment 来获取“X 天前”或“X 天前”,您可以使用moment.from(date)而不是moment.fromNow()并删除所有时间概念。
https://momentjs.com/docs/#/displaying/from/ https://momentjs.com/docs/#/displaying/from/
var today = new Date();
today.setHours(0, 0, 0, 0);
dateToCheck.setHours(0, 0, 0, 0)
moment(dateToCheck).from(today);
or a one-liner或单线
moment(dateToCheck.setHours(0, 0, 0, 0)).from(new Date().setHours(0, 0, 0, 0));
const date1 = moment('06-11-2021')
const date2 = moment('06-12-2021')
const diff = date2.diff(date1, 'days')
console.log("diff: ", diff); // diff: 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.