U
U
Urukhayy2018-01-31 15:47:37
JavaScript
Urukhayy, 2018-01-31 15:47:37

Is it possible to store incorrect time in Date?

In search of an answer to the question "How to get the time in any other time zone from Date", on the English-language site of questions, I came across an interesting version of the answer. They suggest completely ignoring the time zone that Date does, and suggest the following solution, which is given below:

function calcTime(city, offset) {
    // create Date object for current location
    var d = new Date();

    // convert to msec
    // subtract local time zone offset
    // get UTC time in msec
    var utc = d.getTime() - (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time for city"+ city +" is "+ nd.toLocaleString();
}

alert(calcTime('Bombay', '+5.5'));

That is, the time zone shift at the end of the line is completely ignored. And calling this function in different browsers, the new Date method will no longer convert itself to local time. Is it possible to store time and date like this? Is it correct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
deadem, 2018-02-08
@Urukhayy

It is forbidden.
The first problem with this implementation is that, first, there may not be 60,000 milliseconds in a minute.
https://ru.wikipedia.org/wiki/%D0%A1%D0%B5%D0%BA%D...
The second is that we add the time in hours (3600000) to UTC (new Date) , and then we get the time for the current (toLocaleString) time zone, and not for the one for which we consider the time. If the person who runs this code has the transition to winter-summer time in this range, then it will give an incorrect result, since Date will convert dates for the current locale, and not for the one for which the offset was passed.
And what’s more, you can’t generally indicate the offset relative to UTC in hours precisely because of the winter-summer time, you definitely need to know the country and city. Switching to winter-summer time is generally some kind of game, each city may have its own rules for changing the clock, which, moreover, change periodically. Therefore, operating systems carry huge reference books with them for the correct calculation of local time.
Here, for example, what has happened in Russia alone over the past 100 years: https://www.worldtimezone.com/dst_news/dst_news_ru...
The proposed function will almost always return the correct result, but sometimes it will be wrong. So it depends on the purpose of use. It cannot be used for financial documentation. And to display the current time on the site - why not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question