例如,在输入框中给定两个日期:
<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中获得两个日期之间的天数?
当前回答
我来找这个小工具在里面你会找到这个的函数。这里有一个简短的例子:
<script type="text/javascript" src="date.js"></script>
<script type="text/javascript">
var minutes = 1000*60;
var hours = minutes*60;
var days = hours*24;
var foo_date1 = getDateFromFormat("02/10/2009", "M/d/y");
var foo_date2 = getDateFromFormat("02/12/2009", "M/d/y");
var diff_date = Math.round((foo_date2 - foo_date1)/days);
alert("Diff date is: " + diff_date );
</script>
其他回答
从DatePicker小部件使用formatDate怎么样?您可以使用它来转换时间戳格式的日期(从01/01/1970开始的毫秒),然后做一个简单的减法。
function formatDate(seconds, dictionary) {
var foo = new Date;
var unixtime_ms = foo.getTime();
var unixtime = parseInt(unixtime_ms / 1000);
var diff = unixtime - seconds;
var display_date;
if (diff <= 0) {
display_date = dictionary.now;
} else if (diff < 60) {
if (diff == 1) {
display_date = diff + ' ' + dictionary.second;
} else {
display_date = diff + ' ' + dictionary.seconds;
}
} else if (diff < 3540) {
diff = Math.round(diff / 60);
if (diff == 1) {
display_date = diff + ' ' + dictionary.minute;
} else {
display_date = diff + ' ' + dictionary.minutes;
}
} else if (diff < 82800) {
diff = Math.round(diff / 3600);
if (diff == 1) {
display_date = diff + ' ' + dictionary.hour;
} else {
display_date = diff + ' ' + dictionary.hours;
}
} else {
diff = Math.round(diff / 86400);
if (diff == 1) {
display_date = diff + ' ' + dictionary.day;
} else {
display_date = diff + ' ' + dictionary.days;
}
}
return display_date;
}
1970-01-01之前和2038-01-19之后的贡献
function DateDiff(aDate1, aDate2) {
let dDay = 0;
this.isBissexto = (aYear) => {
return (aYear % 4 == 0 && aYear % 100 != 0) || (aYear % 400 == 0);
};
this.getDayOfYear = (aDate) => {
let count = 0;
for (let m = 0; m < aDate.getUTCMonth(); m++) {
count += m == 1 ? this.isBissexto(aDate.getUTCFullYear()) ? 29 : 28 : /(3|5|8|10)/.test(m) ? 30 : 31;
}
count += aDate.getUTCDate();
return count;
};
this.toDays = () => {
return dDay;
};
(() => {
let startDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate1.toISOString()) : new Date(aDate2.toISOString());
let endDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate2.toISOString()) : new Date(aDate1.toISOString());
while (startDate.getUTCFullYear() != endDate.getUTCFullYear()) {
dDay += (this.isBissexto(startDate.getFullYear())? 366 : 365) - this.getDayOfYear(startDate) + 1;
startDate = new Date(startDate.getUTCFullYear()+1, 0, 1);
}
dDay += this.getDayOfYear(endDate) - this.getDayOfYear(startDate);
})();
}
一行代码和小代码
const diff=(e,t)=>Math.floor((new Date(e).getTime()-new Date(t).getTime())/1000*60*60*24);
// or
const diff=(e,t)=>Math.floor((new Date(e)-new Date(t))/864e5);
// or
const diff=(a,b)=>(new Date(a)-new Date(b))/864e5|0;
// use
diff('1/1/2001', '1/1/2000')
为打印稿
const diff = (from: string, to: string) => Math.floor((new Date(from).getTime() - new Date(to).getTime()) / 86400000);
下面是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框架。