Convert UTC date time to local date time

前端 未结 30 1177
悲哀的现实
悲哀的现实 2020-11-22 01:09

From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM and it is in UTC time. I want to convert it to the current user’s browser time us

30条回答
  •  花落未央
    2020-11-22 01:50

    Using YYYY-MM-DD hh:mm:ss format :

    var date = new Date('2011-06-29T16:52:48+00:00');
    date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
    

    For converting from the YYYY-MM-DD hh:mm:ss format, make sure your date follow the ISO 8601 format.

    Year: 
        YYYY (eg 1997)    
    Year and month: 
        YYYY-MM (eg 1997-07)
    Complete date: 
        YYYY-MM-DD (eg 1997-07-16)
    Complete date plus hours and minutes:
        YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)    
    Complete date plus   hours, minutes and seconds:
        YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)    
    Complete date plus hours, minutes, seconds and a decimal fraction of a second
        YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:
    
    YYYY = four-digit year
    MM   = two-digit month (01=January, etc.)
    DD   = two-digit day of month (01 through 31)
    hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
    mm   = two digits of minute (00 through 59)
    ss   = two digits of second (00 through 59)
    s    = one or more digits representing a decimal fraction of a second
    TZD  = time zone designator (Z or +hh:mm or -hh:mm)
    

    Important things to note

    1. You must separate the date and the time by a T, a space will not work in some browsers
    2. You must set the timezone using this format +hh:mm, using a string for a timezone (ex. : 'UTC') will not work in many browsers. +hh:mm represent the offset from the UTC timezone.

提交回复
热议问题