Ruby: combine Date and Time objects into a DateTime

后端 未结 6 1648
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 13:18

Simple question, but I can\'t find a good or definitive answer. What is the best and most efficient way to combine Ruby Date and Time objects (objects, not

6条回答
  •  臣服心动
    2020-12-08 14:04

    If you are using Ruby on Rails, this works great.

    I built a method to extend the DateTime class to combine a date and a time. It takes the zone from the date so that it does not end up an hour off with daylight savings time.

    Also, for convenience, I like being able to pass in strings as well.

    class DateTime
      def self.combine(d, t)
        # pass in a date and time or strings
        d = Date.parse(d) if d.is_a? String 
        t = Time.zone.parse(t) if t.is_a? String
        # + 12 hours to make sure we are in the right zone
        # (eg. PST and PDT switch at 2am)
        zone = (Time.zone.parse(d.strftime("%Y-%m-%d")) + 12.hours ).zone
        new(d.year, d.month, d.day, t.hour, t.min, t.sec, zone)
      end
    end
    

    So you can do:

    DateTime.combine(3.weeks.ago, "9am")
    

    or

    DateTime.combine("2015-3-26", Time.current)
    

    etc...

提交回复
热议问题