skip to Main Content

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)

3

Answers


  1. Before access a particular timezone, you need to load it like so,

    moment.tz.add('Europe/Berlin|CET CEST CEMT|-10 -20 -30')
    

    after adding use this format

    moment(date).tz('Europe/Berlin').format(format)
    

    Zone Add format

    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
  3. Try this…

    import moment from "moment-timezone";
        
    const now = moment(); // Create a moment object representing the current date and time
          const nowInNY = now.tz("America/New_York"); // Convert the moment object to Eastern Timezone
          const formattedTime = nowInNY.format("hh:mm A"); // Format the time as "12-hour format" with AM/PM indicator
          console.log("value", formattedTime)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search