我正在尝试获取两个日期之间的月数
但是由于某种原因,diff方法有时会返回正确的数字,而有时会错误(一个月)(取决于我猜的日期)
var estDate = "some date"; //2022-06-02
estDate = estDate.toString();
var estDateYear = estDate.substring(0,4);
var estDateMonth = estDate.substring(4, 6);
var estDateDay = estDate.substring(6, 8);
estDate = estDateYear + '-' + estDateMonth + '-' + estDateDay;
//first date
estDate = moment(estDate);
//actual date
var date = moment();
//DIFF
var diff= date.diff(estDate, 'month');
diff= diff.toString();
知道为什么会这样吗?
答案 0 :(得分:1)
您应将diff
方法中的第三个参数设置为true。这将返回一个月的分数而不是整数。然后,您可以根据需要舍入以返回所需的数字。
var diff = Math.floor(date.diff(estDate, 'month', true));
文档
https://momentjs.com/docs/#/displaying/difference/
By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument.
答案 1 :(得分:0)
为什么不仅仅使用estDate
来解析moment
字符串?
var estDate = "2022-06-02"; //2022-06-02
estDate = moment(estDate, "YYYY-MM-DD");
//actual date
var date = moment();
//DIFF
var diff= date.diff(estDate, 'month');
diff= diff.toString();
答案 2 :(得分:0)
// Simply use Momentjs Formation library
//let estDate = "2022-06-02";
let estDate = moment("2022-06-02", "YYYY-MM-DD");
let actualdate = moment();
let diff= actualdate.diff(estDate, 'M');
diff= diff.toString();
console.log(diff);
<div>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
</div>