例如,在输入框中给定两个日期:
<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中获得两个日期之间的天数?
当前回答
var start= $("#firstDate").datepicker("getDate");
var end= $("#SecondDate").datepicker("getDate");
var days = (end- start) / (1000 * 60 * 60 * 24);
alert(Math.round(days));
Jsfiddle示例:)
其他回答
我建议使用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
我也有同样的问题,但如果你在SQL查询上做的话会更好:
DateDiff(DAY, StartValue,GETDATE()) AS CountDays
查询将自动生成一个列CountDays
如果我们想计算我们的年龄,这是一个有点不同的答案
{
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);
从DatePicker小部件使用formatDate怎么样?您可以使用它来转换时间戳格式的日期(从01/01/1970开始的毫秒),然后做一个简单的减法。
您可以使用UnderscoreJS来格式化和计算差异。
演示https://jsfiddle.net/sumitridhal/8sv94msp/
var startDate = moment(“206 -08- 29t23:35:01”); var endDate = moment(“206 -08- 30t23:35:01”); 游戏机。log (startDate); 游戏机。log (endDate); var结果= endDate。diff(startDate, hours, true); 文件。 文档全身appendChild(文档。createTextNode (resultHours)); 身体(白色空间:pre;font-family: monospace;) “https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js”< script src = > / < script >