-3

I am based in the UK so when I attempt to parse a new date in JavaScript as follows:

new Date('2016-06-03T09:05:15');

Results in the following date:

Fri Jun 03 2016 10:05:15 GMT+0100 (BST)

I want the date to be parsed as is, and for no locale adjustments (in this instance, BST) to occur. Is this achievable without writing my own date/time parser?

keldar
  • 6,152
  • 10
  • 52
  • 82
  • When dealing with dates, you might want to consider using something like [Moment.js](http://momentjs.com/) or [Date.js](http://www.datejs.com/), which are the de-facto standards for handling this type of operation and might make your life easier. – Rion Williams Jun 03 '16 at 14:46
  • 2
    There's no such thing as an "as is" date -- there is always a locale implied. Closest you can get is do everything in UTC/GMT. – Daniel Beck Jun 03 '16 at 14:48
  • Hey @RionWilliams ironically I am using Date.js :) however, `Date.parse` is not parsing all dates. Am I missing a trick? – keldar Jun 03 '16 at 14:50
  • those two things are different textual representations of the exact same data. –  Jun 03 '16 at 15:28
  • Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) –  Jun 03 '16 at 15:28

1 Answers1

0

I want the date to be parsed as is, and for no locale adjustments (in this instance, BST) to occur

That is exactly what should occur, however it doesn't in all browsers. You should not parse strings using the Date constructor or Date.parse (they are equivalent for parsing). Always manually parse strings, a library can help but usually isn't necessary.

According to EMCAScript 2015, '2016-06-03T09:05:15' should be parsed as a "local" date (i.e. based on the host system settings for date, time and time zone on the date and time supplied). A Date object's time value is UTC, so when creating the time value, the host settings are taken into consideration. The same settings are also used for output, so if the OP string is correctly parsed and then written to output, you should get back exactly the same date and time (though probably in a different format).

If you're seeing a different time from the input string, then the string isn't being correctly parsed (hence advice to manually parse strings).

Is this achievable without writing my own date/time parser?

Yes, use a library that someone else wrote. However, if you also want host settings to be ignored for output, you'll also need to write your own formatter, or use a library.

The good news is that there are many to choose from.

RobG
  • 142,382
  • 31
  • 172
  • 209