JRS: In article <11**********************@z34g2000cwc.googlegroups .com>
, dated Sun, 26 Mar 2006 10:58:58 remote, seen in
news:comp.lang.javascript, blini <fe**********@gmail.com> posted :
Helo.... How I can convert string "26/03/2006 15:51" for a date? I need
to convert and to compare if "09/06/2006 14:20" is lesser or equal that
the current date. Everything in Javascript.
Consider
DS = "26/03/2006 15:51" // UK, EU, etc. field order
function Cvt(ds) {
return new Date(ds.replace(/(..).(..).(....)/, "$3/$2/$1")) }
D = Cvt(DS)
Cvt will convert, presuming exact format, to YYYY/MM/DD hh:mm and then
use new Date() which should be and seems to be everywhere safe with that
string format. You could convert to MM/DD/YYYY, which is unreasonable,
may be safe, and would fail if browsers localised properly. OTOH if
they localised properly you might not want to change the field order.
Your question, as posed, has a problem for one hour in the Autumn in
many countries, where civil time reverses. The code will give the
obviously-correct answer; but that is not necessarily the right one.
I *think* Lasse's method (more foolproof; but that class of fool appears
to be an empty set) would be quicker with new Date(Date.UTC(...)) ,
and its result equally usable.
In my system,
new Date(DS+" GMT") is several times faster than new Date(DS) .
Speed is, however, unlikely to matter to you.
Having done the conversions to Date Objects, compare by subtraction,
which does implicit .valueOf() .
So test is Cvt(DS) <= new Date() if by current date you mean
current date/time. If you want the start of today, which is the true
current date, use .setHours(0,0,0,0) .
Read the newsgroup FAQ.
NOTE : if you need to compare more than one such input with the current
date[/time], then call new Date() once and store the result for
repeated use.
NOTE : if you need to compare many such inputs with the current
date[/time], then call new Date() once, convert it to YYYYMMDDhhmm
format, and store that; omit "new Date"...")" from Cvt and change the
RegExp to give YYYYMMDDhhmm - string comparison is then all that is
needed - but insert a unary + so that Cvt returns a number, since
numerical comparison should be faster.
with (new Date()) YYYYMMDDhhmm =
(((getFullYear()*100 + getMonth()+1)*100 + getDate())*100 +
getHours())*100 + getMinutes()
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.