例如,在输入框中给定两个日期:
<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中获得两个日期之间的天数?
当前回答
要计算两个给定日期之间的天数,可以使用以下代码。我在这里使用的日期是2016年1月1日和2016年12月31日
var day_start = new日期(“2016年1月1日”); var day_end =新的日期(“2016年12月31日”); Var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24); . getelementbyid(“演示”)。innerHTML = Math.round(total_days); <h3>天之间的给定日期</h3> < p id = "演示" > < / p >
其他回答
我也有同样的问题,但如果你在SQL查询上做的话会更好:
DateDiff(DAY, StartValue,GETDATE()) AS CountDays
查询将自动生成一个列CountDays
要计算两个给定日期之间的天数,可以使用以下代码。我在这里使用的日期是2016年1月1日和2016年12月31日
var day_start = new日期(“2016年1月1日”); var day_end =新的日期(“2016年12月31日”); Var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24); . getelementbyid(“演示”)。innerHTML = Math.round(total_days); <h3>天之间的给定日期</h3> < p id = "演示" > < / p >
试试这个
let today = new Date(). toisostring()。片(0,10) const startDate = '2021-04-15'; const endDate = today; const diffInMs = new Date(endDate) - new Date(startDate) const diffInDays = diffInMs / (1000 * 60 * 60 * 24); alert(diffInDays);
夏令时问题使这里的许多答案无效。我将使用一个helper函数来获得给定日期的唯一天数——通过使用UTC方法:
const dayNumber = a => Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()) / (24*60*60*1000); const daysBetween = (a, b) => dayNumber(b) - dayNumber(a); // Testing it const start = new Date(1000, 0, 1); // 1 January 1000 const end = new Date(3000, 0, 1); // 1 January 3000 let current = new Date(start); for (let days = 0; current < end; days++) { const diff = daysBetween(start, current); if (diff !== days) throw "test failed"; current.setDate(current.getDate() + 1); // move current date one day forward } console.log("tests succeeded");
var start= $("#firstDate").datepicker("getDate");
var end= $("#SecondDate").datepicker("getDate");
var days = (end- start) / (1000 * 60 * 60 * 24);
alert(Math.round(days));
Jsfiddle示例:)