0

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

3
  • Have you checked the documentation? The Date.parse() method only parses the date formats it's designed to parse. If you have a date in another format, you'll have to interpret it with your own code or else defer to a library like Moment.js. Commented Dec 8, 2015 at 14:01
  • Thanks @Pointy, I will surely check documentation, I missed that :) Commented Dec 8, 2015 at 14:04
  • var dateCalc = new Date(str); works fine Commented Dec 8, 2015 at 14:05

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I changed the str value. You can check actual format in question I have asked. It works for the format you have pointed out.
@NikhilChavan Check out the updated jsfiddle
0

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.

1 Comment

But what are you trying exactly? Because dateCalc will have a proper Date object which has methods like getDate and such. dateCalc.getDate() I quite can't understand why you are using split and pop over there? Check for example jsfiddle.net/n23v7tun

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.