Date.parse,在ISO格式日期未指定时区时使用本地时区 [英] Date.parse, use local timezone when timezone is not specified in ISO format date

查看:344
本文介绍了Date.parse,在ISO格式日期未指定时区时使用本地时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试搜索这个,没有找到任何内容,所以请先阅读整个问题,然后再标记为重复。



Date.parse的文档指定当ISO格式日期被解析为不包含时区信息,假定UTC(在假定时区的差异部分)。



我有一个没有时区信息的本地datetime字符串: 2015-09-08T11:27:30



如何将Date.parse解析为本地时间? / p>

解决方案

尝试此功能,如此 comment 在类似的问题上。



  function localizeDateStr(date_to_convert_str){var date_to_convert = new Date(date_to_convert_str); var local_date = new Date(); date_to_convert.setHours(date_to_convert.getHours()+(local_date.getTimezoneOffset()/ 60)); return date_to_convert.toString();} alert(localizeDateStr('2015-09-08T11:27:30'));  

p>

这将从本地日期获取时区偏移(除以60,将分钟转换为小时),然后将该小时数添加到您要的字符串中解析的日期本地化然后,将其转换为字符串将显示正确的本地时区与时区。



或者,您只需 return date_to_convert; 来获取日期对象而不是字符串。


I tried searching for this and didn't find anything so please read the whole question before marking as a duplicate.

The documentation for Date.parse specifies that when an ISO format date is parsed that does not contain timezone information, UTC is assumed (Under section "Differences in assumed time zone").

I have a local datetime string with no timezone information: 2015-09-08T11:27:30

How can I get Date.parse to parse this as a local time?

解决方案

Try this function, as mentioned in this comment on a similar question.

function localizeDateStr(date_to_convert_str) {
  var date_to_convert = new Date(date_to_convert_str);
  var local_date = new Date();
  date_to_convert.setHours(date_to_convert.getHours() + (local_date.getTimezoneOffset()/60));
  return date_to_convert.toString();
}

alert(localizeDateStr('2015-09-08T11:27:30'));

This will get the timezone offset from a local date (divide by 60 to convert minutes to hours), then add that number of hours to the date parsed from the string you want to localize. Then, converting it to a string will show you the correct local time with time zone.

Or, you can just return date_to_convert; to get the date object rather than a string.

这篇关于Date.parse,在ISO格式日期未指定时区时使用本地时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆