1

how to convert this

Sun Jan 08 2012 00:00:00 GMT+0530 (Sri Lanka Standard Time)

into

2012-01-08

with javascript?

Regards

Edit:

i was actually working with extjs and didn't know there is a built in way to do this with extjs

so i manage to do this

var date = new Date("Sun Jan 08 2012 00:00:00 GMT+0530 (Sri Lanka Standard Time)");
console.log(Ext.Date.format(date, 'Y-m-d'));

which gives me 2012-01-08

2

2 Answers 2

2

To date contructor you can pass a date string :)

var date = new Date("Sun Jan 08 2012 00:00:00 GMT+0530 (Sri Lanka Standard Time)");
[ date.getFullYear(), date.getMonth() + 1 , date.getDate() + 1 ].join("-");
 //"2012-1-8"
Sign up to request clarification or add additional context in comments.

1 Comment

You can, but the only documented format for that string doesn't match the format the OP tried. Coincidentally, though, I was testing it on various browsers as you posted your answer, though, and all of them seemed happy with it.
2

There's no real shortcut, until the 5th edition (a couple of years ago) there was no standard date string format supported by JavaScript (Date was merely required to correctly parse whatever toString output, without the format actually used by either being specified in the standard), and as of the 5th edition, the format that is explicitly supported for parsing isn't the same as what you've quoted (instead, it's a simplified version of ISO-8601). So you'll have to parse it yourself, using regular expressions and/or brute force (String#indexOf, String#substring, String#split), or use a library (like DateJS) to do it for you.

That said, every browser I tried was happy to parse it for you just via new Date, e.g.:

var str = "Sun Jan 08 2012 00:00:00 GMT+0530 (Sri Lanka Standard Time)";
var dt = new Date(str);

Live example I tried IE6, IE9, Chrome 15, Opera 11, Firefox 9, Firefox 5, Safari 5, Konquerer 4.7.3, and Midori 0.4.0 (spread across Windows and Linux). So if you're happy with that and you test in your target environments (which I don't know are web browsers, JavaScript is used on servers and desktops as well), you may be happy with just doing that.

1 Comment

i was actually working with extjs and didn't know it has a built in way to do this. var date = new Date("Sun Jan 08 2012 00:00:00 GMT+0530 (Sri Lanka Standard Time)"); console.log(Ext.Date.format(date, 'Y-m-d')); which gives me the answer needed 2012-01-08

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.