1

was wondering if someone could advise on I can format the following String to another String in a different format

From this-> var dateString = "January 8, 2013 7:00:00 PM PST"

To This -> dateString = "20130108"'

I don't mind converting this into a Date object if I have too in order to do this, but would like the final result to be a String.

Thanks!

Greg
  • 1,045
  • 4
  • 14
  • 30
  • [This SO Question](http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript) seems to answer your question in detail, it is essential what @Lukas suggested. – fiz Jan 09 '13 at 22:43

1 Answers1

2
var date = new Date(dateString);
var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var properlyFormatted = "" + year + month + day;

Edit: Or as Fiz suggested above, the following:

var date = new Date(dateString);
var properlyFormatted = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2);
Lukas
  • 9,765
  • 2
  • 37
  • 45