Search code examples
javascripttypescriptdatetimetimezone

How to get time difference based on timezone?


I need to get time difference in hours and minutes of other user who is situated in anather country. Here is what i have done.

const timeZone = "Asia/tokyo"; // Time zone can be changed

let arr: any = new Date().toLocaleString("en-US", {
  timeZone: timeZone,
  dateStyle: "full",
  timeStyle: "full",
});

let currentTime = new Date();

Need to get difference between currentHour and arr


Solution

  • Firstly, use en-CA locale for the "calculation" ... it outputs yyyy-mm-dd hh:mm:ss which makes it simple to manipulate

    Secondly, add hour12: false as you want 24 hour time

    Then you can

    const minutesToHHMM = (m) => {
      const s = m < 0 ? '-' : '';
      m = Math.abs(m);
      const mm = (m % 60).toString().padStart(2, 0);
      const hh = Math.floor(m / 60);
      return `${s}${hh}:${mm}`;
    }
    const timeZone = 'Australia/Eucla'; // odd timezone to always show minutes in difference
    const date = new Date();
    date.setMilliseconds(0); // remove millisecond since we are not creating the "other" time with milliseconds
    const other = new Date(...date
      .toLocaleString('en-CA', {
        timeZone,
        hour12: false,
      })
      .replaceAll('-',':') // convert yyyy-mm-dd to yyyy:mm:dd
      .replaceAll(', ', ':') // add ':' between date and time
      .split(':') // split all the values
      .map((v,i) => v - (i===1)) // subtract one from month
    );
    
    console.log("other time", other.toLocaleString());
    console.log("local time", date.toLocaleString());
    console.log("difference", minutesToHHMM((other-date)/60000));

    My Typescript is inelegant ... but

    const minutesToHHMM = (m:number) => {
      const s = m < 0 ? '-' : '';
      m = Math.abs(m);
      const mm = (m % 60).toString().padStart(2, "0");
      const hh = Math.floor(m / 60);
      return `${s}${hh}:${mm}`;
    }
    const timeZone = 'Australia/Eucla'; // odd timezone to always show minutes in difference
    const date = new Date();
    date.setMilliseconds(0); // remove millisecond since we are not creating the "other" time with milliseconds
    
    const other = new Date(...(date
      .toLocaleString('en-CA', {
          timeZone,
          hour12: false,
      })
      .replaceAll('-',':') // convert yyyy-mm-dd to yyyy:mm:dd
      .replaceAll(', ', ':') // add ':' between date and time
      .split(':') // split all the values
      .map(Number)
      .map((v:number, i:number) => v - ((i===1) ? 1 : 0)) as []) // subtract 1 from month
    );
    
    console.log("other time", other.toLocaleString());
    console.log("local time", date.toLocaleString());
    console.log("difference", minutesToHHMM((+other - +date)/60000));
    

    Tried that on a TS Playground, seems to work