Format date in javascript without converting to local timezone

In the SQL database, I have a list of times from different time zones, but I don't have and don't care about the relevant time zone information:

2012-01-01 01:02:03 2012-07-01 04:05:06 

For output, I would like to format them using Javascript. I tried:

 var text = input.replace(' ','T'); // SQL -> ISO8601 var d = new Date(Date.parse(text)); hours = d.getHours(); 

The problem is that in Chrome, the date is interpreted as being in UTC and converted to my local timezone, so I get:

 2 6 

while in Firefox it is interpreted as local time, and I get what I want:

 1 4 

So, is there a better solution with a Date object, or am I stuck in line splitting?

+6
source share
2 answers

The only solution found replaces - with / :

 input = "2012-01-01 01:02:03"; var text = input.replace('-', '/'); var d = new Date(Date.parse(text)); hours = d.getHours(); 

In my case, the input was 2013-05-22T16:45:00Z , so I replaced T and Z :

 input = "2013-05-22T16:45:00Z"; var text = input.replace(/[TZ]/, '').replace('-', '/'); var d = new Date(Date.parse(text)); hours = d.getHours(); 

Thus, Javascript deals with this without knowing anything about the time zone and ceasing to act.

+5
source

I think that for working with dates you need to use some Date framework, for example , jQuery Globalization Plugin or Datejs to get cross-browser behavior. In this case, you can customize the template that will be used in parsing the date.

0
source

Source: https://habr.com/ru/post/923493/


All Articles