最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

firefox - Format a date in Javascript without converting to local timezone - Stack Overflow

programmeradmin0浏览0评论

In an SQL database I have a list of times from different time zones but I neither have nor care for the corresponding time zone information:

2012-01-01 01:02:03
2012-07-01 04:05:06

For outputting I'd like to format them using Javascript. I tried:

var text = input.replace(' ','T'); // SQL -> ISO8601
var d = new Date(Date.parse(text));
hours = d.getHours();

The problem is that in Chrome the the date is interpreted as being in UTC and converted to my local time zone, so I get:

2
6

while in Firefox it's interpreted as local time and I get what I want:

1
4

So is there a better solution with the Date object or am I stuck with splitting the string?

In an SQL database I have a list of times from different time zones but I neither have nor care for the corresponding time zone information:

2012-01-01 01:02:03
2012-07-01 04:05:06

For outputting I'd like to format them using Javascript. I tried:

var text = input.replace(' ','T'); // SQL -> ISO8601
var d = new Date(Date.parse(text));
hours = d.getHours();

The problem is that in Chrome the the date is interpreted as being in UTC and converted to my local time zone, so I get:

2
6

while in Firefox it's interpreted as local time and I get what I want:

1
4

So is there a better solution with the Date object or am I stuck with splitting the string?

Share Improve this question asked Aug 22, 2012 at 15:13 AndreKRAndreKR 33.7k21 gold badges117 silver badges178 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

The only solution I found is replacing - with /:

input = "2012-01-01 01:02:03";
var text = input.replace('-', '/');
var d = new Date(Date.parse(text));
hours = d.getHours();

In my case the input was 2013-05-22T16:45:00Z so I replaced T and Z as well:

input = "2013-05-22T16:45:00Z";
var text = input.replace(/[TZ]/, '').replace('-', '/');
var d = new Date(Date.parse(text));
hours = d.getHours();

That way Javascript deals with it without knowing anything about timezone and stop acting smartly.

I think that to do with Dates you will need to use some Date "framework" like Globalize jQuery plugin or Datejs to get cross-browser behavior. Doing this, you will be able to configure a pattern to be used in the date parsing.

发布评论

评论列表(0)

  1. 暂无评论