javascriptdatetimeunixtimezonedayjs

Convert datetime to user's time


I am using dayjs and trying to achieve a datetime conversion depending on the user's locale.

Example;

The data I have is 15 April 2024 America/Toronto 16:00. I want to convert this to user's timezone - i.e Australia/Sydney or Europe/Paris or wherever they are. Also, the data I get won't be only from America/Toronto, it could be a different timezone, so I need to make that dynamic, too.

I thought unix timestamp has the information of timezone(silly me) so I was trying by that conversion only to realise it didn't work because unix is utc based. I do not want to use momentjs for this and thinking we should be able to do this either by dayjs or vanilla js.


Solution

  • See the documentation for the plugin timezone (GitHub current commit permalink) and the section on formatting (permalink). Here's a runnable snippet to demonstrate:

    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/dayjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/plugin/utc.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/plugin/timezone.js"></script>
    <script type="module">
      // Imported as UMD modules in this demo:
      const {
        dayjs,
        dayjs_plugin_timezone: timezone,
        dayjs_plugin_utc: utc,
      } = window;
    
      dayjs.extend(utc);
      dayjs.extend(timezone);
    
      const dSource = dayjs.tz("2024-04-15 16:00", "America/Toronto"); // in original tz
      const localTimeZone = dayjs.tz.guess();
      const dLocal = dSource.tz(localTimeZone); // in local tz
    
      const formatStr = "YYYY-MM-DD HH:mm:ss";
      const formatted = `${dLocal.format(formatStr)} ${localTimeZone}`;
    
      const tzSydney = "Australia/Sydney";
      const formattedSydney = `${dSource.tz(tzSydney).format(formatStr)} ${tzSydney}`;
    
      console.log("formatted =", formatted) // formatted using your host environment's local time zone
      console.log("formattedSydney =", formattedSydney) // "2024-04-16 06:00:00 Australia/Sydney"
    </script>