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

时间:2016-10-17 05:02:32

标签: javascript angularjs date

我希望找到好几天,两个日期之间存在几个月和几年。 这是我目前正在使用的方法

CalcEnddate = "December 30, 2012"

但它给了我错误的结果。

例如,对于visualEnddate = "March 31, 2013"months = 2,它会返回days = 2,{{1}}的数量。

请帮忙。

3 个答案:

答案 0 :(得分:1)

你可以这么做,

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

答案 1 :(得分:0)

你可以使用momentjs轻松完成。

以下是找到差异的解决方案。

var dateOne = moment();
var dateTwo = moment("2016-10-10T10:00:00");
console.log(moment.duration(dateTwo.diff(dateOne)).humanize());

var dateThree = moment("2014-10-10T10:00:00");
console.log(moment.duration(dateThree.diff(dateOne)).humanize());

var dateFour = moment("2016-10-16T10:00:00");
console.log(moment.duration(dateFour.diff(dateOne)).humanize());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

答案 2 :(得分:0)

javascript逻辑

<html>
<head>
<title>Date substraction</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--

var startDate = prompt("Enter a start date : (mm/dd/yyyy format) ")
var endDate = prompt("Enter a end date: (mm/dd/yyyy format)")

var start_date = Date.parse(startDate);
var end_date = Date.parse(endDate);

var diff_date =  end_date - start_date;

var num_years = diff_date/31536000000;
var num_months = (diff_date % 31536000000)/2628000000;
var num_days = ((diff_date % 31536000000) % 2628000000)/86400000;

document.write("Number of years: " + Math.floor(num_years) + "<br>");
document.write("Number of months: " + Math.floor(num_months) + "<br>");
document.write("Number of days: " + Math.floor(num_days) + "<br>");
//-->
</script>
</body>
</html>

参考:http://www.java2s.com/Tutorial/JavaScript/0240__Date/Getyearmonthanddayfromdatedifference.htm

作为输出返回2个月30天。