我需要解析带有时间戳的字符串,并将其转换为Time
对象。
我正在努力了解Time.parse
的工作方式以及如何忽略DST并始终使用UTC
或直接转换为UTC
时间从GMT
过渡到DST
时,我一直重复几个小时。我尝试过:
Time.parse(t)
Time.parse(t).utc
Time.strptime(t, "%Y-%m-%d %H:%M:%S")
所有结果都相同。这是我的代码的一部分
require 'time'
ts = ["2010-03-28 00:00:00", "2010-03-28 01:00:00", "2010-03-28 02:00:00", "2010-03-28 03:00:00"]
ts.each do |t|
puts "t: #{t} -- pt: #{Time.parse(t)} -- dst: #{Time.parse(t).dst?} -- utc: #{Time.parse(t).utc} -- strptime: #{Time.strptime(t, "%Y-%m-%d %H:%M:%S")}"
end
输出为:
t: 2010-03-28 00:00:00 -- pt: 2010-03-28 00:00:00 +0000 -- dst: false -- utc: 2010-03-28 00:00:00 UTC -- strptime: 2010-03-28 00:00:00 +0000
t: 2010-03-28 01:00:00 -- pt: 2010-03-28 02:00:00 +0100 -- dst: true -- utc: 2010-03-28 01:00:00 UTC -- strptime: 2010-03-28 02:00:00 +0100
t: 2010-03-28 02:00:00 -- pt: 2010-03-28 02:00:00 +0100 -- dst: true -- utc: 2010-03-28 01:00:00 UTC -- strptime: 2010-03-28 02:00:00 +0100
t: 2010-03-28 03:00:00 -- pt: 2010-03-28 03:00:00 +0100 -- dst: true -- utc: 2010-03-28 02:00:00 UTC -- strptime: 2010-03-28 03:00:00 +0100
位置:英国(如果locale
很重要)
时间:DST
Ruby 2.0.0-p247
上的macos
(我无法更改)
编辑
不确定这是黑客,但在时间字符串中添加" UTC"
可解决此问题。查看更新的代码:
require 'time'
ts.map{|t| t + " UTC"}.each do |t|
puts "t: #{t} -- pt: #{Time.parse(t)} -- dst: #{Time.parse(t).dst?} -- utc: #{Time.parse(t).utc} -- \
strptime: #{Time.strptime(t, "%Y-%m-%d %H:%M:%S")}"
end
现在输出为:
t: 2010-03-28 00:00:00 UTC -- pt: 2010-03-28 00:00:00 UTC -- dst: false -- utc: 2010-03-28 00:00:00 UTC -- strptime: 2010-03-28 00:00:00 +0000
t: 2010-03-28 01:00:00 UTC -- pt: 2010-03-28 01:00:00 UTC -- dst: false -- utc: 2010-03-28 01:00:00 UTC -- strptime: 2010-03-28 02:00:00 +0100
t: 2010-03-28 02:00:00 UTC -- pt: 2010-03-28 02:00:00 UTC -- dst: false -- utc: 2010-03-28 02:00:00 UTC -- strptime: 2010-03-28 02:00:00 +0100
t: 2010-03-28 03:00:00 UTC -- pt: 2010-03-28 03:00:00 UTC -- dst: false -- utc: 2010-03-28 03:00:00 UTC -- strptime: 2010-03-28 03:00:00 +0100
当然,最后一次对strptime
的解析是错误的,因为它忽略了UTC
。