Search code examples
momentjsmoment-timezone

How to create a momentJS object with a specfic time and a specific timezone(other than the default local time zone)?


I will receive an string(with time and date) from the frontend. The string format is this "2021-08-16T23:15:00.000Z". I intend to declare a moment object with the input string, along with a specific timezone(other than the local one).

    import moment from "moment";
    import "moment-timezone";



    // The input string I receive from the frontend.
    let strTime = "2021-08-16T23:15:00.000Z";

    console.log(strTime); //2021-08-16T23:15:00.000Z
    let time = moment.tz(strTime,  "YYYY-MM-DDTHH:mm:ss.SSSZ","America/Boise");

    console.log(time); // Moment<2021-08-16T17:15:00-06:00>, undesired value
    let UTCtime = moment.utc(time);
    console.log(UTCtime);

As far as what I understood from this question, console.log(time) should output a moment object of time 23:15:00, but with timezone "America/Boise".

What I intend is time to have the same time i.e "23:15:00.000", with "America/Boise" as timezone. So that when I later convert that time to UTC, I need to get the right value w.r.t the timezone "America/Boise" and not my local timezone. How can I do this.


Solution

  • I figured out a solution.

        const momenttz = require("moment-timezone");
        const moment = require("moment");
        
        // The input string I receive from the frontend.
        let strTime = "2021-08-16T23:15:00.000Z";
        console.log(strTime); //2021-08-16T23:15:00.000Z
        
        let time = moment.utc(strTime);
        time.tz("America/Boise", true);
        console.log(time.tz());
        
        console.log(time); // Moment<2021-08-16T23:15:00-06:00>, desired value
        
        let UTCtime = moment.utc(time);
        console.log(UTCtime); // Moment<2021-08-17T05:15:00Z>
    

    In the above code, at console.log(time),time has the value "23:15:00.000" with required timezone "America/Boise". This makes it possible for you to get the right value , when you later convert it to UTC.

    This is made possible by passing an optional second parameter to .tz mutator of moment-timezone as true which changes only the timezone (and its corresponding offset), and does not affect the time value.

        time.tz(timezone, true);
    

    A sample example of using this is given in the answer code above.

    You can read more about it here in the Moment Timezone Documentation