get timezone from an instance of a dayjs object?

Viewed 502

I have a util method that takes date input and converts it to dayjs instance with timezone conversion is optional.

import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';

const convertDateToLocalFormat= (date = dayjs(), isTimezoneConvesrionRequired = true)=>{
  
  dayjs.extend(utc);
  dayjs.extend(timezone);
  if(isTimezoneConvesrionRequired){
   const tZone = dayjs.tz().guess();
   return dayjs(date).tz(tZone);
  }
  return dayjs(date);

}

** The problem: ** Now if I pass an instance of daysjs object to this function, for which already timezone is applied(in the first iteration), I am getting a date which has two times timezone applied. For example, I am Pacific time zone(browser timezone, let's say 9 am, Feb 5th, 2022). My target time zone is India (I am getting this timezone from my database). So Instead of getting 10.30 pm, Feb 5th, 2022 I am getting 12 am, Feb 6th, 2022.

** My approach: ** If there is a way to get timezone info from a dayjs object, I can check whether the timezone is the same. Something like this.

const instanceTimeZone = date.getTimeZoneInfo() // assuming date is already an instance 
                                               // of dayjs and getTimeZoneInfo() is what 
                                               // I am looking for, some util kind of 
                                               // method
if(isTimezoneConvesrionRequired && instanceTimeZone !== dayjs.tz().guess() ){
   const tZone = dayjs.tz().guess();
   return dayjs(date).tz(tZone);
  }
1 Answers

You could try something like:

const hasTimeZone = myDayJs["$x"]["$timezone"] !== undefined;

The code myDayJs["$x"]["$timezone"] is the only way I've found that can successfully check for an existing time zone on a DayJs object. It will return the time zone name as a string if one exists, or undefined if it does not.

You could also use myDayJs.$x.$timezone and that will give you the same results, but it may give you UI warnings about unresolved variables.

Related