Convert to/from DateTime and Time in Ruby

后端 未结 6 1470
挽巷
挽巷 2020-11-29 16:44

How do you convert between a DateTime and a Time object in Ruby?

6条回答
  •  心在旅途
    2020-11-29 17:21

    Unfortunately, the DateTime.to_time, Time.to_datetime and Time.parse functions don't retain the timezone info. Everything is converted to local timezone during conversion. Date arithmetics still work but you won't be able to display the dates with their original timezones. That context information is often important. For example, if I want to see transactions performed during business hours in New York I probably prefer to see them displayed in their original timezones, not my local timezone in Australia (which 12 hrs ahead of New York).

    The conversion methods below do keep that tz info.

    For Ruby 1.8, look at Gordon Wilson's answer. It's from the good old reliable Ruby Cookbook.

    For Ruby 1.9, it's slightly easier.

    require 'date'
    
    # Create a date in some foreign time zone (middle of the Atlantic)
    d = DateTime.new(2010,01,01, 10,00,00, Rational(-2, 24))
    puts d
    
    # Convert DateTime to Time, keeping the original timezone
    t = Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec, d.zone)
    puts t
    
    # Convert Time to DateTime, keeping the original timezone
    d = DateTime.new(t.year, t.month, t.day, t.hour, t.min, t.sec, Rational(t.gmt_offset / 3600, 24))
    puts d
    

    This prints the following

    2010-01-01T10:00:00-02:00
    2010-01-01 10:00:00 -0200
    2010-01-01T10:00:00-02:00
    

    The full original DateTime info including timezone is kept.

提交回复
热议问题