简体   繁体   English

如何从 javascript 中的字符串获取时区偏移量?

[英]How can I get the timezone offset from string in javascript?

I have a string 2021-04-07T13:51:39.664+11:00 which I use to create a Date object: d = new Date('2021-04-07T13:51:39.664+03:00') .我有一个字符串2021-04-07T13:51:39.664+11:00用于创建Date object: d = new Date('2021-04-07T13:51:39.664+03:00')

After that, d is an instance to represent the date time.之后, d是表示日期时间的实例。 Now I'd like to get the timezone offset from d , but d.getTimezoneOffset() always return local timezone offset which is -600 in my case.现在我想从d获取时区偏移量,但d.getTimezoneOffset()总是返回本地时区偏移量,在我的情况下为-600 How can I get the timezone offset from the string?如何从字符串中获取时区偏移量? Does it get lost when I build the date instance?当我构建date实例时它会丢失吗? Do I have to parse the string to get it?我必须解析字符串才能得到它吗?

If I have a date object, how can I generate a string with the offset at the end: 2021-04-07T13:51:39.664+03:00 ?如果我有一个date object,我怎样才能生成一个带有末尾偏移量的字符串: 2021-04-07T13:51:39.664+03:00 toISOString() only generate UTC time. toISOString()仅生成 UTC 时间。

I know moment is a good date library but I don't want to add this dependency since it is too large.我知道moment是一个很好的日期库,但我不想添加这个依赖项,因为它太大了。

 function dateZ(dateString) { var _date = dateString.substring(0, 23); var _offset = dateString.substring(23); var _dateValue = new Date(dateString); function offset(value) { if (value) { _offset = value; _dateValue = new Date(toString()); } return _offset; } function date(value) { if (value) { _date = value; _dateValue = new Date(toString()); } return _dateValue; } function toString() { return `${_date}${_offset}` } return { offset, date, toString }; } var d = dateZ('2021-04-07T13:51:39.664+03:00'); console.log(d.date(), d.offset(), d.toString()); d.offset('+05:30'); console.log(d.date(), d.offset(), d.toString());

This is probably not the best possible approach, but it is portable and quite useful if you are in control of the application environment.这可能不是最好的方法,但如果您可以控制应用程序环境,它是可移植的并且非常有用。

 friendlyDate = function( x ){ var label = "Day Month Date Year Time Offset".split(" "), d = x? new Date(x): new Date(), s = ( d + "" ).split( / / ); s.length = label.length; for( var x in s )s[ label[ x ] ] = s[ x ]; s.length = 0; return s } /**/ dte = friendlyDate(); for(var x in dte)console.log(x + ": "+ dte[x]);
ps: you might need to readjust\rearrange the labels for certain targeted browsers. ps:您可能需要重新调整\重新排列某些目标浏览器的标签。 [Not all browser vendor\version date string representations are returned equal;)] [并非所有浏览器供应商\版本日期字符串表示形式都相同;)]

How to initialize a JavaScript Date to a particular time zone 如何将 JavaScript 日期初始化为特定时区

There is no time zone or string format stored in the Date object itself.日期 object 本身没有存储时区或字符串格式。

Seems like either string parsing or a library (there are lighter-weight ones than moment if you're interested).看起来像是字符串解析或库(如果您有兴趣,还有比 moment 更轻量级的)。

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

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