Difference between DateTime and Time in Ruby

前端 未结 7 1089
眼角桃花
眼角桃花 2020-11-27 10:03

What\'s the difference between DateTime and Time classes in Ruby and what factors would cause me to choose one or the other?

7条回答
  •  攒了一身酷
    2020-11-27 10:22

    I found such things like parsing and calculating the beginning/end of a day in different timezones are easier to do with DateTime, assuming you are using the ActiveSupport extensions.

    In my case I needed to calculate the end of the day in a user's timezone (arbitrary) based on the user's local time which I received as a string, e.g. "2012-10-10 10:10 +0300"

    With DateTime it's as simple as

    irb(main):034:0> DateTime.parse('2012-10-10 10:10 +0300').end_of_day
    => Wed, 10 Oct 2012 23:59:59 +0300
    # it preserved the timezone +0300
    

    Now let's try it the same way with Time:

    irb(main):035:0> Time.parse('2012-10-10 10:10 +0300').end_of_day
    => 2012-10-10 23:59:59 +0000
    # the timezone got changed to the server's default UTC (+0000), 
    # which is not what we want to see here.
    

    Actually, Time needs to know the timezone before parsing (also note it's Time.zone.parse, not Time.parse):

    irb(main):044:0> Time.zone = 'EET'
    => "EET"
    irb(main):045:0> Time.zone.parse('2012-10-10 10:10 +0300').end_of_day
    => Wed, 10 Oct 2012 23:59:59 EEST +03:00
    

    So, in this case it's definitely easier to go with DateTime.

提交回复
热议问题