Convert date to another timezone in JavaScript

后端 未结 24 3034
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 04:45

I am looking for a function to convert date in one timezone to another.

It need two parameters,

  • date (in format \"2012/04/10 10:10:30 +0000\")
24条回答
  •  攒了一身酷
    2020-11-21 05:25

    I should note that I am restricted with respect to which external libraries that I can use. moment.js and timezone-js were NOT an option for me.

    The js date object that I have is in UTC. I needed to get the date AND time from this date in a specific timezone('America/Chicago' in my case).

     var currentUtcTime = new Date(); // This is in UTC
    
     // Converts the UTC time to a locale specific format, including adjusting for timezone.
     var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
    
     console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
     console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
     console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
     console.log('currentDateTimeCentralTimeZone: ' +        currentDateTimeCentralTimeZone.toLocaleDateString());
     console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
     console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());
    

    UTC is currently 6 hours ahead of 'America/Chicago'. Output is:

    currentUtcTime: 11/25/2016
    currentUtcTime Hour: 16
    currentUtcTime Minute: 15
    
    currentDateTimeCentralTimeZone: 11/25/2016
    currentDateTimeCentralTimeZone Hour: 10
    currentDateTimeCentralTimeZone Minute: 15
    

提交回复
热议问题