Question

How do I format the following to a 'mm/dd/yyyy h:mm:ss' date in javascript?

/Date(-62135571600000)/
Was it helpful?

Solution

In my current time zone:

new Date(-62135571600000); //=> Mon Jan 01 1 02:00:00 GMT-0500 (Eastern Standard Time)

Is that what you're looking for? So you can easily pull out the date properties you want from that object to format it as you like...

OTHER TIPS

// create a new date object from the timestamp...
var p = (new Date(-62135571600000)).toISOString().split(/\D+/)
// format the date
var formatted = [p[1],p[2],p[0]].join("/")+" "+[p[3],p[4],p[5]].join(":")
// check it...
alert(formatted)

(new Date(-62135571600000)) returns a date object, which when output as a string looks like... Mon Jan 01 1 07:00:00 GMT+0000 (GMT). Internally, javascript understands it as a date. Next, we convert it .toISOString(), so the format looks more like... 0001-01-01T07:00:00.000Z - which is ISO standard date format. Next, we split it into an array by any non-digit characters using regex (.split(/\D+/)), which gives us something like... ["0001", "01", "01", "07", "00", "00", "000", ""]. Finally, we assign that to a variable... var p = ....

Now we have the date parts in the p array, we can assemble them as we wish. Firstly, joining the parts 1, 2 and 0 (0 is year, 1 is month, 2 is day) with slashes ([p[1],p[2],p[0]].join("/")) giving 0001-01-01. Next we add a space ...+" "+... and join the times together... [p[3],p[4],p[5]].join(":"). Assign the result to a variable... var formatted = ... and we are good to go!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top