skip to Main Content

I have a string "2024-09-19 14:20:45" in given time zone say "America/Los_Angeles".
In javascript how can I convert it to datetime string in another time zone "timezone2" say "America/New_York" (three hours earlier than Los Angeles)?

How can I get "2024-09-19 17:20:45" in the above example for "America/New_York" in Javascript ?

2

Answers


  1. const inputDateStr = "2024-09-19 14:20:45";
    const timezone1 = "America/Los_Angeles";
    const timezone2 = "America/New_York";
    
    // Convert inputDateStr to a Date object in UTC, assuming it's in timezone1
    const dateInLA = new Date(`${inputDateStr} UTC`);
    
    // Use Intl.DateTimeFormat to convert the date to timezone2
    const options = {
      timeZone: timezone2,
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    };
    
    const dateFormatter = new Intl.DateTimeFormat('en-US', options);
    const parts = dateFormatter.formatToParts(dateInLA);
    
    const formattedDate = `${parts[4].value}-${parts[0].value}-${parts[2].value} ${parts[6].value}:${parts[8].value}:${parts[10].value}`;
    
    console.log(formattedDate); // "2024-09-19 17:20:45"

    In this approach:

    new Date(): We parse the string and assume it’s UTC.

    Intl.DateTimeFormat: This is used to format the date into the desired time zone, America/New_York.

    Login or Signup to reply.
  2. Lets try that in Luxon, since JS has crummy timezone handling

    const convertTimeZone = (inputDateStr, fromTimeZone, toTimeZone) => {
      const { DateTime } = luxon; // Access Luxon from global object
    
      // Parse the date in the fromTimeZone
      const dateInFromZone = DateTime.fromFormat(inputDateStr, 'yyyy-MM-dd HH:mm:ss', {
        zone: fromTimeZone
      });
    
      // Convert to the target time zone
      const dateInTargetZone = dateInFromZone.setZone(toTimeZone);
    
      // Return the formatted date in the target time zone
      return dateInTargetZone.toFormat('yyyy-MM-dd HH:mm:ss');
    };
    
    const inputDateStr = "2024-09-19 14:20:45";
    const timezoneLA = "America/Los_Angeles";
    const timezoneNY = "America/New_York";
    const timezoneTaipei = "Asia/Taipei";
    
    
    console.log('Time in NY', convertTimeZone(inputDateStr, timezoneLA, timezoneNY));
    
    
    console.log('Time in Taipei', convertTimeZone(inputDateStr, timezoneLA, timezoneTaipei))
    <script src="https://cdn.jsdelivr.net/npm/luxon@2/build/global/luxon.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search