admin管理员组文章数量:1327450
hi could you please tell me how to find difference of dates using moments js? here is my code
/
secondDate "2019-12-01" // formate YYYY-MM-DD;
var day = moment().format('YYYY-MM-DD');
// difference of secondDate - date
alert('day'+secondDate - day)
Can we calculate the difference of years between two dates
expected output
3
hi could you please tell me how to find difference of dates using moments js? here is my code
https://jsfiddle/FLhpq/6082/
secondDate "2019-12-01" // formate YYYY-MM-DD;
var day = moment().format('YYYY-MM-DD');
// difference of secondDate - date
alert('day'+secondDate - day)
Can we calculate the difference of years between two dates
expected output
3
Share Improve this question edited Sep 14, 2016 at 10:09 user944513 asked Sep 14, 2016 at 10:06 user944513user944513 12.7k52 gold badges185 silver badges348 bronze badges 3-
there is a method called
diff()
– Satpal Commented Sep 14, 2016 at 10:08 -
I need differnce in year as example it should give
3
– user944513 Commented Sep 14, 2016 at 10:08 - Possible duplicate of JavaScript : How to Calculate number of days between two dates using javascript – Rajesh Commented Sep 14, 2016 at 10:14
4 Answers
Reset to default 6You can leverage on various methods i.e. diff()
, asYears()
var firstDate = moment("2013-12-01", 'YYYY-MM-DD'); //Create date using string-format constructor
var secondDate = moment("2016-12-01", 'YYYY-MM-DD');
var duration = moment.duration(secondDate.diff(firstDate));
var years = duration.asYears();
console.log(years)
console.log(Math.round(years))
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.5.1/moment.min.js"></script>
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);
var years = a.diff(b, 'year');
console.log(years + ' years);
<html>
<head>
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.9.0/moment.js"></script>
<script>
var a = moment("2016-11-04","YYYY-MM-DD");
var b = moment("2000-11-04","YYYY-MM-DD");
alert(a.diff(b, 'years')+" Year");
</script>
</head>
let firstDate = moment("11/07/2023","DD/MM/YYYY")
let today = moment(new Date());
let diff1 = firstDate.diff(today, 'days'); //for days
let diffYears = firstDate.diff(today, 'years'); //for years
console.log(diff1). //1
本文标签: javascripthow to find difference of dates in years using moments jsStack Overflow
版权声明:本文标题:javascript - how to find difference of dates in years using moments js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742212292a2433933.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论