Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news.albasani.net!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.javascript Subject: Re: Date arithmetic Date: Wed, 26 Nov 2014 22:07:34 +0100 Organization: PointedEars Software (PES) Lines: 55 Message-ID: <1643585.kn8vp8Llee@PointedEars.de> References: <0d947d29-c683-4417-b081-983f18bb11bf@googlegroups.com> Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit X-Trace: solani.org 1417036065 8519 eJwNx8EBwCAIA8CVpCSBjiMW9h/B3u/oMp2AKHA4jjpYJpv1ceTZMYW/m9WJnarX2G0TVY3nAhsGEWI= (26 Nov 2014 21:07:45 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Wed, 26 Nov 2014 21:07:45 +0000 (UTC) User-Agent: KNode/4.14.2 X-User-ID: eJwNyskRACEIBMCUlGNkwmFB8g9hrepnu2KjjsFhPj6KNDpJpZlXy4eQGK13Hk6lMOTmPqsbK7osccm7SyPuDzbGFTA= Cancel-Lock: sha1:OuulTYKquRGGI0r4Lpwh0ChphVk= X-NNTP-Posting-Host: eJwNyMkRACAIBLCWuHa1HUHovwSd/AKnslYQDMx3SJXJbA27dd1ql6eCsJHm/jWCOrTW1f4AIqgRTQ== Xref: csiph.com comp.lang.javascript:26215 RobG wrote: > Consider: Considered, and rejected :) > // Parse a y-m-d string as UTC > // Value separator can be any non-digit (e.g. / or .) > // Return NaN if invalid date You may want to read . > function parseUTCymd(s) { > var b = s.split(/\D/); > var d = new Date(Date.UTC(b[0], --b[1], b[2])); There is no need to pre-decrement b[1] because you are not reusing the value. “b[1] - 1” is more obvious, maybe even more efficient, than --b[1]. > return d.getFullYear() == b[0] && d.getDate() == b[2]? d : NaN; > } > > // Return difference in days given string dates > // in format y-m-d. > // If either date is invalid, returns NaN > function daysDiff(d0, d1) { > var a = parseUTCymd(d0); > var b = parseUTCymd(d1); > return isNaN(a) || isNaN(b) ? NaN : Math.round((b - a)/8.64e7); > } > […] > > This approach only works for whole days. Math.round is probably not > required, but provides comfort should there be an insignificant error in > the time values. Apparently you have missed the much simpler solution suggested by Christoph on 2014-11-13 and the subthread that followed: pp. I prefer that over this, with perhaps the exception of the parsing (this one’s is more flexible). However, in my opinion the condition that causes the parsing to be required should be eliminated in advance: There should be three separate controls for a date that are reduced to one when a type="date" control is supported, and then not its “value” property but its “valueAsDate” or ”valueAsNumber” property should be used. -- PointedEars FAQ: | SVN: Twitter: @PointedEars2 | ES Matrix: Please do not cc me. / Bitte keine Kopien per E-Mail.