Convert a time to a specific timezone in moment timezone

左心房为你撑大大i 提交于 2021-01-28 09:35:30

问题


I have a date 2018-06-19 09:06:29. It is how it is stored in the database. I am using moment-timezone and calling this function.

function getDateString(t, tz) {
    return moment()
    .tz("America/Chicago")
    .format('l');
}

Here I know that my timezone is "America/Chicago" and it is "UTC-5 hours". I should get the time 5 hours before the time that I have passed as an argument.

This function was working perfectly until I upgraded my react. Can anyone know what might be the issue?

These are my current settings of react

"expo": "^27.0.0",
"moment": "^2.22.2",
"react": "16.3.1",
"react-moment": "^0.7.0",
"moment-timezone": "^0.5.17",
"react-native": "https://github.com/expo/react-native/archive/sdk-27.0.0.tar.gz",
"react-native-swipeable": "^0.6.0",
"react-navigation": "1.5.11"

回答1:


As per my comments, not sure exactly what is going wrong (and how it used to work on your side), but here is how it should work to me :

  1. Create a moment with your date time, specifying that this is expressed as utc, with moment.utc()

  2. convert it to your timezone with moment.tz()

This would give something like :

function getDateString(t, tz) {
    return moment.utc(t, 'YYYY-MM-DD HH:mm:ss')
    .tz("America/Chicago")
    .format('l');
}


来源:https://stackoverflow.com/questions/50926142/convert-a-time-to-a-specific-timezone-in-moment-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!