0

I want to parse a date into a javascript date object. I am using the following

new Date(Date.parse('2012-08-01'))

The problem is my input date can be in multiple formats and parsing it should always give me the date object with the date as

2012-08-01 00:00:00

in local timezone.

What are possible options in javascript without using any third party libraries ?

I have a possible solution. But my concern is should i be worried that this will not work in certain android/iphone/kindle/surface native browsers?

var timezone = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1];
var dateObject = new Date(Date.parse('2012-08-01 '+timezone));
3
  • when you say no 3rd party libraries, are you talking about JS framework agnosticism? (ie no jQuery/mooTools etc.) or not even working with vanilla JS libraries? Commented Jun 5, 2014 at 5:15
  • specifically mooTools...I use Jquery in my app, but dont want to add more dependencies. native javascript is ok. What are you referring to when u say vanialla JS libraries? Commented Jun 5, 2014 at 5:17
  • Jacob Wright created this JS version of PHP's date format abilities that just uses plain JS (aka vanilla JS) jacwright.com/projects/javascript/date_format this might be a step in the right direction in terms of formatting and updating for local timezone, couple that with something like var tz = -(new Date().getTimezoneOffset()*60); // user timezone offset returned in sec and you should be pretty sorted Commented Jun 5, 2014 at 5:24

1 Answer 1

1

Replace the dashes with forward slashes and it will use the local time. Be sure to use yyyy/mm/dd ordering if you want it to work everywhere.

You also do not need to explicitly call Date.parse. The Date constructor will do that when you pass a string.

new Date('2012/08/01')  // local
new Date('2012-08-01')  // UTC

Yes, JavaScript is weird.

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.