例如,在输入框中给定两个日期:
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>
如何在JavaScript中获得两个日期之间的天数?
例如,在输入框中给定两个日期:
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>
如何在JavaScript中获得两个日期之间的天数?
当前回答
下面是datediff的快速实现,作为解决问题的概念证明。它依赖于这样一个事实,即您可以通过减去两个日期之间经过的毫秒,这将它们强制转换为原始数字值(自1970年初以来的毫秒)。
/** * Take the difference between the dates and divide by milliseconds per day. * Round to nearest whole number to deal with DST. */ function datediff(first, second) { return Math.round((second - first) / (1000 * 60 * 60 * 24)); } /** * new Date("dateString") is browser-dependent and discouraged, so we'll write * a simple parse function for U.S. date format (which does no error checking) */ function parseDate(str) { var mdy = str.split('/'); return new Date(mdy[2], mdy[0] - 1, mdy[1]); } alert(datediff(parseDate(first.value), parseDate(second.value))); <input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/>
You should be aware that the "normal" Date APIs (without "UTC" in the name) operate in the local timezone of the user's browser, so in general you could run into issues if your user is in a timezone that you don't expect, and your code will have to deal with Daylight Saving Time transitions. You should carefully read the documentation for the Date object and its methods, and for anything more complicated, strongly consider using a library that offers more safe and powerful APIs for date manipulation.
数字和日期——MDN JavaScript指南 日期——MDN JavaScript参考
同样,出于说明的目的,为了简洁起见,该代码段对窗口对象使用了命名访问,但在生产中应该使用getElementById之类的标准化api,或者更有可能使用一些UI框架。
其他回答
使用Moment.js
Var future = moment('05/02/2015'); Var start = moment('04/23/2015'); Var d =未来。diff(开始,“天”);/ / 9 console.log (d); < script src = " https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js " > < /脚本>
function validateDate() {
// get dates from input fields
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
var sdate = startDate.split("-");
var edate = endDate.split("-");
var diffd = (edate[2] - sdate[2]) + 1;
var leap = [ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
var nonleap = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
if (sdate[0] > edate[0]) {
alert("Please enter End Date Year greater than Start Date Year");
document.getElementById("endDate").value = "";
diffd = "";
} else if (sdate[1] > edate[1]) {
alert("Please enter End Date month greater than Start Date month");
document.getElementById("endDate").value = "";
diffd = "";
} else if (sdate[2] > edate[2]) {
alert("Please enter End Date greater than Start Date");
document.getElementById("endDate").value = "";
diffd = "";
} else {
if (sdate[0] / 4 == 0) {
while (sdate[1] < edate[1]) {
diffd = diffd + leap[sdate[1]++];
}
} else {
while (sdate[1] < edate[1]) {
diffd = diffd + nonleap[sdate[1]++];
}
}
document.getElementById("numberOfDays").value = diffd;
}
}
如果我们想计算我们的年龄,这是一个有点不同的答案
{
birthday: 'April 22, 1993',
names: {
first: 'Keith',
last: 'Buckley'
}
},
{
birthday: 'January 3, 1975',
names: {
first: 'Larry',
last: 'Heep'
}
},
{
birthday: 'February 12, 1944',
names: {
first: 'Linda',
last: 'Bermeer'
}
}
];
const cleanPeople = people.map(function ({birthday, names:{first, last}}) {
// birthday, age, fullName;
const now = new Date();
var age = Math.floor(( Date.parse(now) - Date.parse(birthday)) / 31536000000);
return {
age,
fullName:`${first} ${last}`
}
});
console.log(cleanPeople);
console.table(cleanPeople);
我建议使用moment.js库(http://momentjs.com/docs/#/displaying/difference/)。它正确地处理夏令时,通常是很好的工作。
例子:
var start = moment("2013-11-03");
var end = moment("2013-11-04");
end.diff(start, "days")
1
下面是datediff的快速实现,作为解决问题的概念证明。它依赖于这样一个事实,即您可以通过减去两个日期之间经过的毫秒,这将它们强制转换为原始数字值(自1970年初以来的毫秒)。
/** * Take the difference between the dates and divide by milliseconds per day. * Round to nearest whole number to deal with DST. */ function datediff(first, second) { return Math.round((second - first) / (1000 * 60 * 60 * 24)); } /** * new Date("dateString") is browser-dependent and discouraged, so we'll write * a simple parse function for U.S. date format (which does no error checking) */ function parseDate(str) { var mdy = str.split('/'); return new Date(mdy[2], mdy[0] - 1, mdy[1]); } alert(datediff(parseDate(first.value), parseDate(second.value))); <input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/>
You should be aware that the "normal" Date APIs (without "UTC" in the name) operate in the local timezone of the user's browser, so in general you could run into issues if your user is in a timezone that you don't expect, and your code will have to deal with Daylight Saving Time transitions. You should carefully read the documentation for the Date object and its methods, and for anything more complicated, strongly consider using a library that offers more safe and powerful APIs for date manipulation.
数字和日期——MDN JavaScript指南 日期——MDN JavaScript参考
同样,出于说明的目的,为了简洁起见,该代码段对窗口对象使用了命名访问,但在生产中应该使用getElementById之类的标准化api,或者更有可能使用一些UI框架。