Convert UTC date time to local date time

前端 未结 30 1534
悲哀的现实
悲哀的现实 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条回答
  •  萌比男神i
    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;
    };
    

提交回复
热议问题