How to calculate the difference of two dates in js and so that the timezone difference does not affect?

  • 0
    There are tasks on the site, a person starts to complete a task at a certain point in time, he has a deadline, let's say 1 day or 6 hours.
    The server works in Moscow, I want to calculate the difference between the current time (MSK) and the time when it needs to complete the task (MSK).
    I managed to get in js always MSC time like this
    function getMoscowDate() {
                let d = new Date();
                let utc = d.getTime() + (d.getTimezoneOffset() * 60000);
                return  new Date(utc + (3600000*3));
            }


    The end date is served in this format Sat 14 Nov 2020 11:59:41 GMT + 0300
    As a result, I go to the site and try to create this date (new Date (Date.parse (endtime))), it gives, say, an hour later from Moscow time, for example, if the user has the time of Kiev +2.

    A function that calculates the difference.
    funcjs['getTimeRemaining'] = function (endtime) {
                var t = Date.parse(endtime) - Date.parse(getMoscowDate());
                var seconds = Math.floor((t / 1000) % 60);
                var minutes = Math.floor((t / 1000 / 60) % 60);
                var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
                var days = Math.floor(t / (1000 * 60 * 60 * 24));
                return {
                    'total': t > 0 ? t : 0,
                    'days': days > 0 ? days : 0,
                    'hours': hours > 0 ? hours : 0,
                    'minutes': minutes > 0 ? minutes : 0,
                    'seconds': seconds > 0 ? seconds : 0
                };
            }


    In general, I hope it is clear that you need to get the difference between the current and future time in Moscow time, because all the different time zones are confusing, it is not clear how to do this.
    JavaScript Jane Travis, Dec 29, 2018

  • 2 Answers
  • 0
    The above told you everything. Store in utc in the database. Operate utc on the client too, but do the user output with the time zone or, as an option, highlight utc and local time.
    Anonymous

  • 0
    Instead of a strange method for calculating Moscow time, it is better to write like this.

    ...
    var t = Date.parse(endtime) - Date.now();
    ...
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!