Here is a quick and dirty implementation of datediff
, as a proof of concept to solve the problem as presented in the question.
(这是datediff
的快速而肮脏的实现,作为解决问题中提出的问题的概念证明。)
It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).(它依赖于这样一个事实,您可以通过减去两个日期来获得两个日期之间经过的毫秒数,这会将它们强制为原始数字值(自1970年初以来的毫秒数)。)
// new Date("dateString") is browser-dependent and discouraged, so we'll write // a simple parse function for US date format (which does no error checking) function parseDate(str) { var mdy = str.split('/'); return new Date(mdy[2], mdy[0]-1, mdy[1]); } function datediff(first, second) { // Take the difference between the dates and divide by milliseconds per day. // Round to nearest whole number to deal with DST. return Math.round((second-first)/(1000*60*60*24)); } 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.
(您应该注意,“常规”日期API(名称中没有“ UTC”)在用户浏览器的本地时区中运行,因此通常,如果用户所在的时区不是您所在的时区,则可能会遇到问题期望,并且您的代码将必须处理夏令时转换。)
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.(您应该仔细阅读有关Date对象及其方法的文档,对于任何更复杂的内容,强烈建议您使用提供更安全和强大的API进行日期处理的库。)
Also, for illustration purposes, the snippet uses named access on the window
object for brevity, but in production you should use standardized APIs like getElementById , or more likely, some UI framework.
(同样,出于说明目的,该代码段为了简洁起见在window
对象上使用了命名访问 ,但是在生产中,您应该使用标准化的API,如getElementById或更可能是某些UI框架。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…