例如,输入框中给出两个日期:
<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"/>
您应该注意,“正常”Date API(名称中不带“UTC”)在用户浏览器的本地时区中运行,因此,如果您的用户位于您不属于的时区,通常您可能会遇到问题预计,您的代码将必须处理夏令时转换。您应该仔细阅读 Date 对象及其方法的文档,对于任何更复杂的内容,请强烈考虑使用为日期操作提供更安全和更强大的 API 的库。
- 数字和日期 -- MDN JavaScript 指南 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates
- Date-- MDN JavaScript 参考 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Also, for illustration purposes, the snippet uses named access on the window object https://www.w3.org/TR/html5/browsers.html#named-access-on-the-window-object for brevity, but in production you should use standardized APIs like getElementById https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById, or more likely, some UI framework.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)