在Ruby中解析字符串到时间(Time.parse)时如何忽略DST

时间:2019-05-22 18:52:52

标签: ruby time utc dst datetime-parsing

我需要解析带有时间戳的字符串,并将其转换为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

0 个答案:

没有答案