I'm receiving a date from a data source which is returned to javascript code.
2011-01-03T05:53:00Z
What is the best way to format this date? The TZ doesn't need to be offset as the users will all be in the same zone, I need a method to simply format it.
开发者_如何学JAVA03/01/2011 05:53:00
I have already done this in a couple of lines with replace() but is there a more elegant solution?
Using back reference:
var dat = "2001-08-01T12:00:00Z";
var newDat = dat.replace(/(\d{4})-(\d{2})-(\d{2})T([0-9:]+)Z/, "$2/$3/$1 $4");
alert(newDat);
A first solution would be to rely on a regular expression, but after checking, at least with V8, the Date constructor do accept the string you have as a source as a valid date string.
var date = new Date("2011-01-03T05:53:00Z")
creates a valid Date object. You can then use the Date methos to create the string you which to use.
see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date for more information on the Date object.
I did it like this - it works in IE8, Fx3.6, Safari4, Chrome as opposed to the un-edited string which works in Fx but not in several other browsers:
new Date('2001-01-01T12:00:00Z'.replace(/\-/g,'\/').replace(/[T|Z]/g,' '))
but I am sure someone will post a REGEX with backreferencing :)
精彩评论