简体   繁体   English

如何在 javascript 中将时区偏移设为 ±hh:mm?

[英]How to get timezone offset as ±hh:mm in javascript?

I can get the Timezone offset with the following command as:我可以使用以下命令获取时区偏移量:

new Date().getTimezoneOffset() -> -330 and using moment new Date().getTimezoneOffset() -> -330 和使用时刻

moment().utcOffset() as 330. moment().utcOffset()为 330。

However, how do I get the format as ±hh:mm?但是,如何获得 ±hh:mm 格式?

Are you trying to achieve this?您是否正在努力实现这一目标? If you prefer moment.js you can use .format for formatting date or time.如果你更喜欢moment.js ,你可以使用.format来格式化日期或时间。

 const date = new Date(); let utc = moment(date).utcOffset() console.log(moment.utc(date).utcOffset(utc).format('h:mm A ZZ')) let utc2 = date.getTimezoneOffset(); console.log(moment.utc(date).utcOffset(utc2).format('h:mm A ZZ'))
 <script src="https://momentjs.com/downloads/moment.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Update: Is this according to your expected output? 更新:这是否符合您预期的 output?

 const date = new Date(); let utc = moment(date).utcOffset() console.log(moment(date).utcOffset(utc).format())
 <script src="https://momentjs.com/downloads/moment.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Reference: Display参考:显示

You won't be able to do it without a third-party library or manually converting the value with functionality.如果没有第三方库或使用功能手动转换值,您将无法做到这一点。

You can do something like:您可以执行以下操作:

const offset = new Date().getTimezoneOffset();
let offsetHours = parseInt(Math.abs(offset/60));
let offsetMins = Math.abs(offset%60);
let formattedOffset;

if (offsetHours < 10) offSetHours = '0' + offsetHours;
if (offsetMins < 10) offsetMins = '0' + offsetMins;

if (offset < 0) {
  formattedOffset = '+' + offsetHours + ':' + offsetMins;
} else if (offset > 0) {
  formattedOffset = '-' + offsetHours + ':' + offsetMins;
} else if (offset === 0) {
 formattedOffset = 'Z';
}

That should get you pretty close.那应该让你非常接近。

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

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