简体   繁体   English

在 JS [UTC+2、UTC+3、UTC-12 等] 中使用数值设置 UTC 时区

[英]Setting UTC timezone with numeric values in JS [UTC+2, UTC+3, UTC-12, etc]

How can I create a date with a specific timezone like that [UTC+2, UTC+3, UTC-12, etc] but not with string like that 'America/New York' in js/moment.js?如何创建具有特定时区的日期,例如 [UTC+2、UTC+3、UTC-12 等],但不能在 js/moment.js 中使用像“美国/纽约”这样的字符串? I have a list of all timezones from server in this format [UTC+2, UTC+3, UTC-12, etc], so I need to create dates with a choosen timezone.我有一个来自服务器的所有时区列表,格式为 [UTC+2、UTC+3、UTC-12 等],因此我需要使用选定的时区创建日期。 I tried to use moment.js but it accepts only strings formate.我尝试使用 moment.js 但它只接受字符串格式。 Thanks ahed!谢谢啊!

I tried to use moment.js but...我尝试使用 moment.js 但是...

Didn't you come accross those methods: .utc() , .add() and .format() ?您没有遇到过这些方法: .utc().add().format()吗?

EDIT编辑

To accomodate non-full hour offsets, you can use .match to retreive the sign (+ or -) of the offset, the hour and the optionnal minute.要适应非整小时偏移,您可以使用.match检索偏移的符号(+ 或 -) 、小时和可选分钟。

Here is the actual possible offsets list:Wikipedia这是实际可能的偏移量列表:Wikipedia

It outputs UTC time if your offset only is UTC or is an empty string.如果您的偏移量仅为UTC或为空字符串,它将输出 UTC 时间。

 const timeOffsets = ["UTC+2", "UTC+3", "UTC-12", "UTC+5:45", "UTC-3:30", "UTC", ""] function getlocalTime(offset) { const time = offset.match(/([\+\-])(\d{1,2}):?(\d{2})?/) let sign = "" let numericOffset = 0 if (time) { sign = time[1] numericOffset = parseInt(time[2]) + (time[3] ? parseInt(time[3]) / 60 : 0) } return moment().utc().add(sign + numericOffset, "hours").format("YYYY-MM-DD HH:mm:ss") } const result = timeOffsets.map(getlocalTime) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM