jquery 如何使用moments js查找年份中的日期差异?

7rfyedvj  于 2023-08-04  发布在  jQuery
关注(0)|答案(4)|浏览(93)

你好,可以告诉我如何使用moments js查找日期的差异吗?这是我的代码
https://jsfiddle.net/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)

字符串
我们能计算出两个日期之间的年差吗

预期输出

3

lrpiutwd

lrpiutwd1#

您可以使用各种方法,即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))

个字符

bkkx9g8r

bkkx9g8r2#

var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);

var years = a.diff(b, 'year');

console.log(years + ' years);

字符串

uhry853o

uhry853o3#

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/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>

字符串

vcirk6k6

vcirk6k64#

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

字符串

相关问题