gpt4 book ai didi

javascript - 在javascript中查找给定两天之间存在的天数、月数和年数

转载 作者:行者123 更新时间:2023-12-03 05:52:48 25 4
gpt4 key购买 nike

我想查找两个日期之间存在多少天、几个月和几年。这是我目前正在使用的方法

 $scope.getForcastPeriod = function(newValue){

var CalcEnddate;
var forecastDays;



var CalcEnddate = new Date($scope.forecastObj.paramObj.enddate);
var visualEnddate = new Date($scope.visualDate.enddate);

var diff = new Date(visualEnddate - CalcEnddate);

var years = (diff.getFullYear() - 1970);
var months = (diff.getMonth()) + (12 * years);
var days = (diff.getDate()) + (365 * years);

var months = $scope.monthDiff(CalcEnddate,visualEnddate);


if($scope.forecastObj.paramObj.interval == "Yearly"){
forecastDays = years+1;
}
else if($scope.forecastObj.paramObj.interval == "Monthly"){
forecastDays = months+1;
}
else if($scope.forecastObj.paramObj.interval == "Daily"){
forecastDays = days;
}

return forecastDays ;

}

但它给了我错误的结果。

例如,对于 CalcEnddate = "December 30, 2012"visualEnddate = "March 31, 2013"它返回我的号码 months = 2 , days = 2

请帮忙。

最佳答案

你可以简单地这样做,

var date1 = new Date("12/30/2012");
var date2 = new Date("3/31/2013");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var diffmonths = Math.ceil(timeDiff / (1000 * 3600 * 24 *12));
alert("DAYS"+ " " +diffDays);
alert("MONTHS"+ " " + diffmonths);

JSFIDDLE

关于javascript - 在javascript中查找给定两天之间存在的天数、月数和年数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40078777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com