【问题标题】:New DateTime instead of String in rubyruby 中的新日期时间而不是字符串
【发布时间】:2017-10-24 21:58:56
【问题描述】:

我在 Ruby 中遇到了一些关于 DateTime 的问题 我的行看起来像这样(在 .txt 文件中)

DateTime.new(1979,1,1) DateTime.new(2012,3,29)

我得到这个的函数看起来像这样

def split_line
  array = line.split(' ')
  @date_of_birth = array[0] 
  @date_of_death = array[1] 
end

但是@date_of_birth@date_of_death 类是字符串。我怎样才能将它们作为 DateTime?

【问题讨论】:

  • 您是否将行传递给函数?当前行未定义
  • 你有一个字符串"DateTime.new(1979,1,1) DateTime.new(2012,3,29)"?为什么?
  • 这很可能是一个“XY Problem”。为什么你的文本文件中有那一行?

标签: ruby-on-rails ruby datetime


【解决方案1】:

如果您想要 DateTime 值,请获取数字并创建它们:

require 'date'

'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split.map { |s|
  DateTime.new(*s.scan(/\d+/).map(&:to_i) )
}
# => [#<DateTime: 1979-01-01T00:00:00+00:00 ((2443875j,0s,0n),+0s,2299161j)>,
#     #<DateTime: 2012-03-29T00:00:00+00:00 ((2456016j,0s,0n),+0s,2299161j)>]

这些值不是 DateTime,而是 Dates:

'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split.map { |s|
  Date.new(*s.scan(/\d+/).map(&:to_i) )
}
# => [#<Date: 1979-01-01 ((2443875j,0s,0n),+0s,2299161j)>,
#     #<Date: 2012-03-29 ((2456016j,0s,0n),+0s,2299161j)>]

分解:

'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split # => ["DateTime.new(1979,1,1)", "DateTime.new(2012,3,29)"]
  .map { |s|
  Date.new(
    *s.scan(/\d+/) # => ["1979", "1", "1"], ["2012", "3", "29"]
    .map(&:to_i) # => [1979, 1, 1],       [2012, 3, 29]
  )
}
# => [#<Date: 1979-01-01 ((2443875j,0s,0n),+0s,2299161j)>,
#     #<Date: 2012-03-29 ((2456016j,0s,0n),+0s,2299161j)>]

更大的问题是为什么您会在文本文件中获得类似的值。

【讨论】:

    【解决方案2】:

    这个:

    DateTime.new(1979,1,1) DateTime.new(2012,3,29)
    

    不是代码。你希望它做什么?

    如果您想要两个 DateTimes 作为空格分隔的字符串,请执行以下操作:

    "#{DateTime.new(1979,1,1)} #{DateTime.new(2012,3,29)}" 
    

    当您在一组双引号中包含 #{...} 之类的内容(它们必须是双引号,而不是单引号)时,它被称为 string interpolation。学习它。爱它。活下去。

    但是,为了我的一生,我不知道你为什么不这样做:

    [DateTime.new(1979,1,1), DateTime.new(2012,3,29)]
    

    这会给你一个array,所以不需要split。只是:

    def split_line
      @date_of_birth = array[0] 
      @date_of_death = array[1] 
    end
    

    【讨论】:

      【解决方案3】:

      假设您的字符串格式正确,那么您可能正在寻找:

      @date_of_birth = array[0].to_datetime
      @date_of_death = array[1].to_datetime
      

      查看这里了解更多信息:

      https://apidock.com/rails/String/to_datetime

      【讨论】:

        猜你喜欢
        • 2015-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-27
        • 2010-12-22
        • 2019-09-07
        • 2010-09-07
        • 1970-01-01
        相关资源
        最近更新 更多