JRS: In article <dc********@news1.newsguy.com>, dated Thu, 28 Jul 2005
14:44:20, seen in news:comp.lang.javascript, Matt Kruse
<ne********@mattkruse.com> posted :
mike wrote: I have a data like:
03-Jul-05
and need to convert it to:
7/3/2005
Is there a function for this already?
There are a number of date function libs around.
Using mine from http://www.javascripttoolbox.com/date/ you could simply do:
var d = "03-Jul-05";
var formatted = formatDate(new
Date(getDateFromFormat(d,"d-MMM-yy")),"M/d/yyyy");
If your case is very specific, you could surely avoid using a big library
and instead use regular expressions to perform the task. Less code, but also
less flexibility. Depends on what you really need.
Since he indicated an exact input format, it is reasonable to assume
that anything else is impossible or erroneous.
PS: Ignore John Stockton's comment which is surely coming, complaining about
converting from a good format to a dumb "American" one. :)
It's nice to see that at least one American here recognises that the US
format is dumb. There can be no doubt that M/D/YYYY is American; FFF is
used nowhere outside the unofficial American Empire (presumably much of
Iraq is now infested with it). So his quotes around 'American' are not
needed : OTOH, because he did not include 'dumb' within the quotes, it
is clear that he accepts the description 'dumb'.
To do the job only with a RegExp requires the use of a function in the
replacement. This looks simpler :
d = "03-Jul-05"
A = d.replace(/0?([1-9]?\d)-(\w\w\w)-(\d\d)/, "/$1/20$3")
A = "xxxJanFebMarAprMayJunJulAug...".indexOf(RegExp.$2 )/3 + A
Use of RegExp.$2 may be deprecated, but it will no doubt be possible to
avoid it.
Note that malformed input may give surprise results; if the input is not
assuredly [#]#-Mon-##, checks will be needed.
Note that the above could be easily adapted to provide Y M D as numbers,
which could easily be loaded into a Date Object, validated, and output
in a programmer-defined manner. See my pages js-date3.htm etc.
Eschew bloatware; it imposes an unnecessary burden on everyone who
downloads the code, which means all readers of pages using it. How many
lines do formatDate and getDateFromFormat need?
--
© 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.