如何将这些字符串解析为 UTC 日期?
我正在抓取一个网站,日期有两种形式:
11-22-2011 07:41 AM
Today @ 07:41 AM
这两种形式都是 GMT-8。我想从中获取一个unix时间戳,以便我可以构造一个有意义的日期对象
知道这可能是什么时区吗?大约一个月前,该网站显示 GMT-9 时间。 javascript可以自动处理夏令时吗?
我很难解析它们。部分问题在于时区。
目前,我正在使用 Date.js 的 parseExact
:
date = Date.parseExact(date + ' PDT', 'MM-dd-yyyy H:mm tt zzz');
然而,这似乎将上午 12 点解析为 12:00
,而不是 0:00
代码>.此外,我完全不知道如何处理以 today @
开头的内容。
I'm scraping a site, and the dates come in two forms:
11-22-2011 07:41 AM
Today @ 07:41 AM
Both of these are GMT-8. I'd like to get a unix timestamp out of these, so that I can construct a meaningful date object
Any idea what timezone this might be? Around a month ago, the site was gibing GMT-9 times. Can javascript handle Daylight Saving Time automatically?
I'm having great difficultly parsing them. Part of the problem is the time zone.
At the moment, I'm using Date.js' parseExact
:
date = Date.parseExact(date + ' PDT', 'MM-dd-yyyy H:mm tt zzz');
Hovever, this seems to get parse 12AM as 12:00
, not 0:00
. Additionally, I'm at a total loss as to how to handle the ones starting with today @
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当我使用 http://www.datejs.com/ 上的交互式解析器尝试您的两个示例时,我得到预期结果。
有问题的时区可能是“美国西海岸”,又名“太平洋时间”。
不幸的是,这在一年中的不同时间意味着不同的事情。在春季和夏季,该时区称为“PDT”(GMT-0700),其余时间称为“PST”(GMT-0800)。
更复杂的是,更改的日期与其他区域(例如欧洲)更改的日期不同。
我认为没有一种方法可以为 Date.js 指定时区值来自动考虑这一点。
When I try both of your examples using the interactive parser at http://www.datejs.com/ I get the expected results.
The timezone in question is likely "US West Coast", aka "Pacific Time".
Unfortunately that means different things at different times of the year. In the spring and summer that timezone is called "PDT" (GMT-0700) and the rest of the time it's called "PST" (GMT-0800).
To further complicate matters the dates on which that changes aren't the same as the dates on which other zones (e.g. in Europe) change.
I don't think there's a way of specifying a timezone value to Date.js that can take that into account automatically.
您可以编写自己的时区感知日期解析逻辑,该逻辑会考虑远程服务器的时区。
伪代码:
You could write your own, timezone-aware date parsing logic which takes into account the timezone of the remote server.
pseudo-code:
为什么不直接添加
HHHH:mm zzz
来获取 12:00?Why not just add
HHHH:mm zzz
to get 12:00?使用小写
h
表示小时即可得到 1-12。大写的H
给出 0-23。 的格式从您的示例中,我将使用文档
您应该处理“Today @ ”分别地。当您找到该字符串时,预计下一个标记是
hh:mm tt
形式的时间。将第二部分解析为时间并将其与今天(本地)日期结合起来。使用 Date.js 函数以编程方式实现这一点并不难,但您不会找到捕获“Today @”部分的单个格式字符串(如您所知)。Use a lowercase
h
for the hour to get 1-12. The uppercaseH
gives 0-23. From your examples I would use a format ofDocumentation
You should handle "Today @ " separately. When you find that string, expect the next token to be a time in the form
hh:mm tt
. Parse the second part as a time and combine it with today's (local) date. That is not hard to do programmatically with Date.js functions, but you won't find a single format string that captures the "Today @" part (as you know).