Join the DZone community and get the full member experience.Join For Free
you know that one piece of shitty code that always makes you cringe? something along the lines of months = ['jan', 'feb' ....]; datestring = date.day()+’ ‘+months[date.month()];
yeah that piece of code. let’s talk about that .
a couple of days ago i caught myself writing code like that and red flags and alarms and air-raid sirens started going off in my head. i felt like that proverbial axe murderer reading my code who knows where i live was already breathing down my neck.
scary situation that.
string -> date
// all of this correctly returns a millisecond timestamp since unix epoch // the string argument can also be passed to the date constructor by the way (returns a correct date object) date.parse("aug 9, 1995") date.parse("wed, 09 aug 1995 00:00:00 gmt") date.parse("wed, 09 aug 1995 00:00:00") date.parse("thu, 01 jan 1970 00:00:00 gmt") date.parse("thu, 01 jan 1970 00:00:00") date.parse("thu, 01 jan 1970 00:00:00 gmt-0400")
date -> string
have a date and want a string? you’re shit out of luck son.
> var d = new date() > d mon, 12 dec 2011 11:28:55 gmt > d.tostring() 'mon dec 12 2011 12:28:55 gmt+0100 (cet)' > d.todatestring() 'mon dec 12 2011' > d.toisostring() '2011-12-12t11:28:55.401z' > d.tojson() '2011-12-12t11:28:55.401z' > d.togmtstring() 'mon, 12 dec 2011 11:28:55 gmt' > d.tolocaledatestring() 'monday, december 12, 2011' > d.tolocalestring() 'mon dec 12 2011 12:28:55 gmt+0100 (cet)' > d.tolocaletimestring() '12:28:55' > d.tostring() 'mon dec 12 2011 12:28:55 gmt+0100 (cet)' > d.totimestring() '12:28:55 gmt+0100 (cet)' > d.toutcstring() 'mon, 12 dec 2011 11:28:55 gmt'
notice how none of those functions accept a format parameter? sure, you could get those strings and hack them apart to create a string formatted to your liking … but i’m not sure that’s the ideal approach.
and let’s not even get into wanting to coerce a 12-hour time format out of this thing. perhaps if your computer is situated in the us the localestring would return that?
however i was able to find a jquery plugin that implements a rough strftime function , although it doesn’t seem to have been actively worked on for the past three years and there are many things missing.
Opinions expressed by DZone contributors are their own.