javascriptmoment-timezone

change time base on timezone momen-timezone


i want to convert selected time into timezone saved in user profile using moment-timezone library

my local system timezone is PKT(pakistan) and user has saved timezone in his Profile is AEST(australian/sydney). so when user select time i just want that time in userTimezone and send in API. e.g

const time  =  "07:00"
const date = "06/13/2023"
const timezone = "Australian/Sydney"
moment(`${date} ${time}`).tz(timezone).format() // 2023-06-20T12:00:00+10:00

converted time should be 7Am AESt but library has convert it into 12pm. if i change moment default timezone into user profile timezone then still i dont get correct output

e.g

const time  =  "07:00"
const date = "06/13/2023"
const timezone = "Australian/Sydney"
 moment.tz.setDefault(timezone)

 moment(`${date} ${time}`).tz(timezone).format() //2023-06-20T12:00:00+10:00
 moment(`${date} ${time}`).format() //2023-06-20T12:00:00+10:00
moment.tz(`${date} ${time}`, timezone).format() // 2023-06-20T17:00:00+10:00

you can see none of the output is what i am trying to acheive. it would be greate if you let me know other library if moment does not support this.


Solution

  • I could not solve this issue with moment-timezone library and so I shifted to dayjs it solved my problem. it is correctly converting time in selected timezone.

    Here is my code for this:

    import dayjs from "dayjs";
    import utc from "dayjs/plugin/utc"; // Import the UTC plugin for dayjs
    import timezone from "dayjs/plugin/timezone";
    import customParseFormat from "dayjs/plugin/customParseFormat";
    
    // Extend dayjs with the required plugins
    dayjs.extend(utc);
    dayjs.extend(timezone);
    dayjs.extend(customParseFormat);
    
    const getStartAndEndDateTime = (date, time, timezone, duration) => {
      let startDateTime = "";
      let endDateTime = "";
    
      if (date && time) {
        const formateDDate = dayjs(date).format("YYYY-MM-DD");
        const formatedTime = dayjs(time, "hh:mm a").format("H:mm");
        const timestamp = `${formateDDate} ${formatedTime}`;
    
        startDateTime = dayjs.tz(timestamp, timezone || dayjs.tz.guess()).format();
        endDateTime = dayjs
          .tz(timestamp, timezone || dayjs.tz.guess())
          .add(duration.value, "m")
          .format();
      }
      return { start_datetime: startDateTime, end_datetime: endDateTime };
    };