Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.datemas.de!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: "Christoph M. Becker" Newsgroups: comp.lang.javascript Subject: Re: Date arithmetic Date: Thu, 13 Nov 2014 15:27:03 +0100 Organization: solani.org Lines: 47 Message-ID: References: <111120142237479787%timstreater@greenbee.net> Mime-Version: 1.0 Content-Type: text/plain; charset=iso-8859-15 Content-Transfer-Encoding: 7bit X-Trace: solani.org 1415888816 13453 eJwNyMEBwCAIA8CVQoUg40gN+4/Q3vNi0fimM+gxMVjYo5FlPt0kUqTuUf97a4DcdZwyMrzsAylZEUY= (13 Nov 2014 14:26:56 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Thu, 13 Nov 2014 14:26:56 +0000 (UTC) User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Thunderbird/31.2.0 X-User-ID: eJwFwYEBwCAIA7CXRGkZ5wjS/09YgkNjhxN0CHqZ9amnG5VMFpTPZcvNgztgd2tjefWcuPMDKMsRQA== In-Reply-To: Cancel-Lock: sha1:qaq2eKplsIdsTC5hv9uU7AVRv/A= X-NNTP-Posting-Host: eJwNyMEBgDAIA8CVQEgo64hk/xHqPQ9B51QSTAjiNz7y/ww2HZLTyiOLXFu9sThdFdb98MwFEqsQUA== Xref: csiph.com comp.lang.javascript:26131 Evertjan. wrote: > "Christoph M. Becker" wrote on 12 nov 2014 in > comp.lang.javascript: > > The code I provided can be used on selected clientside and serverside > platforms, so please can we discuss the code: > > ======================== > function dateDifference(d0, d1) { > > var msPerDay = 8.64e7; > > // make JS-dates from string parameters > var x0 = new Date(d0); > var x1 = new Date(d1); > > // set both to noon to minimize DST errors > x0.setHours(12,0,0); > x1.setHours(12,0,0); > > // substract and then round to remove DST errors > return Math.round( (x1 - x0) / msPerDay ); > > }; > ========================= In the given case (there is no time involved), I would work around any potential DST issues by using Date.UTC(). Parsing the date strings is slightly more complex, but the calculations should be exact (not even Math.round() is needed). function daysBetween(isoDay1, isoDay2) { var msPerDay = 24 * 60 * 60 * 1000, isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/, parts, timestamp1, timestamp2; parts = isoExp.exec(isoDay1); timestamp1 = Date.UTC(parts[1], parts[2] - 1, parts[3]); parts = isoExp.exec(isoDay2); timestamp2 = Date.UTC(parts[1], parts[2] - 1, parts[3]); return Math.abs(timestamp2 - timestamp1) / msPerDay; } -- Christoph M. Becker