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));
Community
  • 1
  • 1
Whimsical
  • 5,985
  • 1
  • 31
  • 39
  • 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? – haxxxton Jun 05 '14 at 05: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? – Whimsical Jun 05 '14 at 05:17
  • Jacob Wright created this JS version of PHP's date format abilities that just uses plain JS (aka vanilla JS) http://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 – haxxxton Jun 05 '14 at 05:24

1 Answers1

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575