Convert date to another timezone in JavaScript

后端 未结 24 3035
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 04:45

I am looking for a function to convert date in one timezone to another.

It need two parameters,

  • date (in format \"2012/04/10 10:10:30 +0000\")
24条回答
  •  既然无缘
    2020-11-21 05:43

    I was having trouble using Moment Timezone. I am adding this answer just so if somebody else faces the same issue. So I have a date string 2018-06-14 13:51:00 coming from my API. I know that this is stored in UTC but the string doesn't speak for itself.

    I let moment timezone know, what timezone this date is from by doing:

    let uTCDatetime = momentTz.tz("2018-06-14 13:51:00", "UTC").format();
    // If your datetime is from any other timezone then add that instead of "UTC"
    // this actually makes the date as : 2018-06-14T13:51:00Z
    

    Now I would like to convert it to a specific timezone by doing:

    let dateInMyTimeZone = momentTz.tz(uTCDatetime, "Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss");
    // now this results into: 2018-06-14 19:21:00, which is the corresponding date in my timezone.
    

提交回复
热议问题