在 moment js 中将已知时区的时间转换为本地时区
Convert time of a known timezone to local timezone in moment js
我正在尝试使用 Moment.js.
将时间(单独时间)从已知时区转换为我的本地时区
我编写了以下函数,并且得到 invalidDate
作为输出。
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, tz)
const localTime = t.local()
}
time
只是时间;没有任何日期,例如:10:06 am
和
tz
是时区字符串,例如:Europe/Berlin
我做错了什么?
The moment.tz
constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
由于您的输入 (10:06 am
) 不是 ISO 8601/RFC 2822 可识别的格式(参见 moment(String)
docs), you have to pass format parameter as shown in moment(String, String)
。
这里是一个活生生的例子:
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, 'hh:mm a', tz)
const localTime = t.local()
return localTime;
}
const res = convertToLocalTime("10:06 am", 'Europe/Berlin');
console.log( res.format('hh:mm a') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data-2012-2022.min.js"></script>
我正在尝试使用 Moment.js.
将时间(单独时间)从已知时区转换为我的本地时区我编写了以下函数,并且得到 invalidDate
作为输出。
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, tz)
const localTime = t.local()
}
time
只是时间;没有任何日期,例如:10:06 am
和tz
是时区字符串,例如:Europe/Berlin
我做错了什么?
The
moment.tz
constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
由于您的输入 (10:06 am
) 不是 ISO 8601/RFC 2822 可识别的格式(参见 moment(String)
docs), you have to pass format parameter as shown in moment(String, String)
。
这里是一个活生生的例子:
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, 'hh:mm a', tz)
const localTime = t.local()
return localTime;
}
const res = convertToLocalTime("10:06 am", 'Europe/Berlin');
console.log( res.format('hh:mm a') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data-2012-2022.min.js"></script>