Convert date to another timezone in JavaScript

后端 未结 24 3021
没有蜡笔的小新
没有蜡笔的小新 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:18

    Having looked around a lot including links from this page i found this great article, using moment timezone:

    https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/

    To summarise it:

    Get the user's timezone

    var tz = moment.tz.guess();
    console.info('Timezone: ' + tz);
    

    Returns eg: Timezone: Europe/London

    Set the default user timezone

    moment.tz.setDefault(tz);
    

    Set custom timezone

    moment.tz.setDefault('America/Los_Angeles');
    

    Convert date / time to local timezone, assumes original date/time is in UTC

    moment.utc('2016-12-25 07:00').tz(tz).format('ffffd, Do MMMM YYYY, h:mma');
    

    Returns: Sun, 25th December 2016, 7:00am

    Convert date/time to LA Time

    moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ffffd, Do MMMM YYYY, h:mma');
    

    Returns: Sat, 24th December 2016, 11:00pm

    Convert from LA time to London

    moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ffffd, Do MMMM YYYY, h:mma' );
    

    Returns: Sun, 25th December 2016, 3:00pm

提交回复
热议问题