Nikhil Chavan
Nikhil Chavan

Reputation: 1715

Javascript datetime parsing from string

I am trying to parse a string to javascript Date object, I tried different ways to parse it to Date but none of them seems to work. Initially I was thinking it will be easy to parse string to Date as JavaScript Date has constructor that takes a string or I would use Date.parse() method but it seems that I was wrong.

Here is string for date format- 2015-12-01 00:28:28.1271204 +01:00

What I have tried so far-

var dateCalc = new Date(str);
var dateCalc = Date.parse(str);

Please this JSFiddle - http://jsfiddle.net/D7c28/12/

Please suggest solution for this. Please let me know if I am missing something.

Thanks :)

Upvotes: 0

Views: 5844

Answers (2)

iplus26
iplus26

Reputation: 2647

It works fine for me:

var str = "Fri, 15 Nov 2013 09:00:00 -0600"
var date = new Date(str);

console.log(date.getDate())  // 15

date is a Date object with many methods like getDate(). Check out the documentation.

Update:

2015-12-01 00:28:28.1271204 +01:00 seems not to be a valid date for the default constructor (but works fine in node on my Mac). So I use moment.js and it works fine.

Check out the updated jsfiddle.

Upvotes: 2

Shiroo
Shiroo

Reputation: 666

I'm almost sure that

var dateString = "2015-12-01 00:28:28.1271204 +01:00";
var dateCalc = new Date(dateString);

Will work (dateCalc) will have a proper date (that is, Tue Dec 01 2015 00;28:28 GMT+0100.

If you want to be a more flxeible with the solution you always can try MomentJS which gives you a lot of possibilties with format, localization and such stuff.

Upvotes: 0

Related Questions