Greg
Greg

Reputation: 1055

Convert Full Date String in javascript to yyyymmdd

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!

Upvotes: 1

Views: 7691

Answers (1)

Lukas
Lukas

Reputation: 9845

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);

Upvotes: 2

Related Questions