Search code examples
javascriptreactjsangularmomentjsmoment-timezone

(moment-timezone). convert time from one timezone to another timezone


I am in India, and selecting time 9:00 AM, and timezone eg. 'America/Dawson' and I want to convert time according to selected timezone to 'America/New_York' timezone.But Not getting result

    var currentDate = new Date()
    currentDate.setHours(9, 0, 0);
    moment.tz.setDefault('America/Dawson')
    var currentDateMom = moment(currentDate)
    var oldTimezoneTime = currentDateMom.tz('America/New_York').format('YYYY-MM-DD HH:mm:ss ZZ');
    console.log(oldTimezoneTime)

Solution

  • We can use the moment.tz constructor to create our moment object with the correct year, month, day, hour etc values.

    This will create a moment date in the America/Dawson timezone with the date set to the current date and time to 09:00.

    We can then use the .tz() function to convert to the new timezone (America/New_York)

    function getTimeInTimezone(year, month, day, hour, minute, second, timeZone) {
        // Construct using an array of date elements...
        const dateArr = [year, month, day, hour, minute, second];
        return moment.tz(dateArr, timeZone);
    }
    
    const now = new Date()
    
    const year = now.getFullYear();
    const month = now.getMonth();
    const day = now.getDate();
    const hour = 9;
    
    const originalTimeZone = 'America/Dawson';
    const newTimeZone = 'America/New_York';
    
    const timeInOriginalTimeZone = getTimeInTimezone(year, month, day, hour, 0, 0, originalTimeZone);
    const timeInNewTimeZone = moment(timeInOriginalTimeZone).tz(newTimeZone);
    
    console.log('Timezone'.padEnd(20), 'Time');
    console.log(originalTimeZone.padEnd(20), timeInOriginalTimeZone.format('YYYY-MM-DD HH:mm:ss'));
    console.log(newTimeZone.padEnd(20), timeInNewTimeZone.format('YYYY-MM-DD HH:mm:ss'));
    <script src="https://momentjs.com/downloads/moment.js"></script>
    <script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>