Clock belt problem with javascript date



  • There's a problem with dates in different browsers. Let's say there are two dates that go to JSON as a server text:

    Array [ "2015-11-11T12:01:00", "2015-11-23T09:44:00" ] 
    

    Target: For the view by which the user sets time (used) bootstrap-timepicker.jsvariable type used Date♪ It is necessary to fill this date from the server, regardless of the time belt, and also to return after the change.

    For that, I get a text date from the server, create a variable. new Date("2015-11-11T12:01:00")♪ Obviously, for the record, new Date takes the current timeline of the user. So, I just dropped the clock belt, no problem, only time. However, Chromium The time is further changed according to the time belt. Chromium:

    Wed Nov 11 2015 15:01:00 GMT+0300 (MSK)
    Было: 2015-11-11T12:01:00
    

    Mon Nov 23 2015 12:44:00 GMT+0300 (MSK)
    Было: 2015-11-23T09:44:00

    There is no such problem in Iceweasel:

    "Wed Nov 11 2015 12:01:00 GMT+0300 (MSK)"
    Было: "2015-11-11T12:01:00"

    "Mon Nov 23 2015 09:44:00 GMT+0300 (MSK)"
    Было: "2015-11-23T09:44:00"

    If I break the entry line with the date-time and try to make a date-time in UTC, the result is the same:

    Got a year, a month, a day.

    ["2015", "11", "23"]

    An hour, minutes, seconds

    ["09", "44", "00"]

    new Date(Date.UTC(year, month-1, day, hour, min))

    As a result, Chromium provides:

    Wed Nov 23 2015 12:44:00 GMT+0300 (MSK)

    Iceweasel is still all ok:

    Array [ "2015", "11", "23" ]
    Array [ "09", "44", "00" ]
    Date 2015-11-23T09:44:00.000Z



  • First, we have to make the same behavior in different browsers. To this end, the letter Z should be added at the end of the stringular presentation of the date, thus clearly indicating that the date is in UTC.


    To obtain the date and time in the same way as they were sent from the server, we can use UTC-Functions:

    var d = new Date("2015-11-11T12:01:00Z")
    d.getUTCHours() // 12
    d.toUTCString() // Wed, 11 Nov 2015 12:01:00 GMT
    

    If you need an object Date that would give the same meaning in the challenge of conventional methods, you can do this:

    var d = new Date("2015-11-11T12:01:00Z")
    d = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds())
    d.getHours() // 12
    d.toString() // Wed Nov 11 2015 12:01:00 GMT+0500 (RTZ 4 (зима))
    

    This method will be useful as a crutch if the library you use has no UTC mode of operation.


    I suggest, however, that we consider whether there is a problem in the setting itself? Usually, when the server operates UTC, and the user displays all the dates at the local time is a perfectly normal situation and should be.

    PS Look towards the library http://momentjs.com/


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2