Search code examples
javascriptdatedatetimemomentjsmoment-timezone

Convert date string to date with timezone using moment timezone js


I need to convert a date string to PDT (Pacific Daylight Time) and the resutant datetime must be displayed in local time.

I tried with

console.log(moment.tz("16:23:42 Sep 27, 2018 PDT", 'HH:mm:ss MMM DD, YYYY PDT',"PDT").format());

When I run the above code it displays

2018-09-27T16:23:42Z

Which is not the local time. The local time of its equivalent must be different. How do I get the local time of the date string specified.

In otherwords, I mean to say like this https://forums.asp.net/t/1552114.aspx?Convert+Datetime+String+from+PDT+to+IST+local+time+datetime+string


Solution

  • You can try this, i think it will work

    first get timezone offset timeZoneId is your time zone.

    const offset =  moment['tz'](moment(new Date()), timeZoneId).utcOffset() * 60000;
    

    secondly create new datefrom your date and your offset

    console.log(new Date(new Date(yourDateString).getTime() + offset))
    

    and yes yourDateString is your date string, better works for date obj, but w/e