Convert UTC date time to local date time

前端 未结 30 1033
悲哀的现实
悲哀的现实 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:24

    This is an universal solution:

    function convertUTCDateToLocalDate(date) {
        var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
    
        var offset = date.getTimezoneOffset() / 60;
        var hours = date.getHours();
    
        newDate.setHours(hours - offset);
    
        return newDate;   
    }
    

    Usage:

    var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
    

    Display the date based on the client local setting:

    date.toLocaleString();
    
    0 讨论(0)
  • 2020-11-22 01:26

    To me the simplest seemed using

    datetime.setUTCHours(datetime.getHours());
    datetime.setUTCMinutes(datetime.getMinutes());
    

    (i thought the first line could be enough but there are timezones which are off in fractions of hours)

    0 讨论(0)
  • 2020-11-22 01:26

    I believe this is the best solution:

      let date = new Date(objDate);
      date.setMinutes(date.getTimezoneOffset());
    

    This will update your date by the offset appropriately since it is presented in minutes.

    0 讨论(0)
  • 2020-11-22 01:27

    For the TypeScript users, here is a helper function:

    // Typescript Type: Date Options
    interface DateOptions {
      day: 'numeric' | 'short' | 'long',
      month: 'numeric',
      year: 'numeric',
      timeZone: 'UTC',
    };
    
    // Helper Function: Convert UTC Date To Local Date
    export const convertUTCDateToLocalDate = (date: Date) => {
      // Date Options
      const dateOptions: DateOptions = {
        day: 'numeric',
        month: 'numeric',
        year: 'numeric',
        timeZone: 'UTC',
      };
    
      // Formatted Date (4/20/2020)
      const formattedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000).toLocaleString('en-US', dateOptions);
      return formattedDate;
    };
    
    0 讨论(0)
  • 2020-11-22 01:28

    This works for me:

    function convertUTCDateToLocalDate(date) {
        var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
        return newDate;   
    }
    
    0 讨论(0)
  • 2020-11-22 01:28

    You can use momentjs ,moment(date).format() will always give result in local date.

    Bonus , you can format in any way you want. For eg.

    moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
    moment().format('ffffdd');                    // Friday
    moment().format("MMM Do YY"); 
    

    For more details you can refer Moment js website

    0 讨论(0)
提交回复
热议问题