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!

1
  • This SO Question seems to answer your question in detail, it is essential what @Lukas suggested. Commented Jan 9, 2013 at 22:43

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.