I\'m trying to get JavaScript to parse a date and time format for me, with the eventual aim of telling me the days passed since that date and the time right now (locally).
it must be a string that is recognizable by the parse() function.
http://www.devguru.com/technologies/javascript/10585.asp look at the dateString param
The correct syntax should be:
var thedate = "Oct 1, 2008 06:21:43"; var inmillisecs = new Date(thedate);
You have to take some steps to transform the String you're receiving into the format I showed. Using the american format also works
var thedate = "10/1/2008 06:21:42"; var inmillisecs = new Date(thedate);
This should do it
function dateFromUTC( dateAsString, ymdDelimiter )
{
var pattern = new RegExp( "(\\d{4})" + ymdDelimiter + "(\\d{2})" + ymdDelimiter + "(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})" );
var parts = dateAsString.match( pattern );
return new Date( Date.UTC(
parseInt( parts[1] )
, parseInt( parts[2], 10 ) - 1
, parseInt( parts[3], 10 )
, parseInt( parts[4], 10 )
, parseInt( parts[5], 10 )
, parseInt( parts[6], 10 )
, 0
));
}
alert( dateFromUTC( "2008-10-01 06:21:43", '-' ) );
The expected format is the American format: m/d/yyyy hh:mm:ss
var date1 = new Date("2008-10-01 06:21:43"); //fails
var date2 = new Date("10/1/2008 06:21:43"); //works correctly
There's this nice looking library called DateJS. I have no experience with it, but you might find it useful. I think you'd be particularly interested in parse()
and/or parseExact()
.
I originally heard about it from this SO post.
Cheers.
EDIT: I just noticed your mention of time and I'm not sure DateJS handles times so I'm going to look into that real quick, or else you can just ignore this post :)
That's an ISO 9601 date -- they're a nice standard to work with. Try just munging it using regular expressions:
(\d{4})-(\d{2})-(\d{2})[ tT](.*)
to
\2/\3/\1 \4