Convert to/from DateTime and Time in Ruby

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

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

6条回答
  •  庸人自扰
    2020-11-29 17:12

    Improving on Gordon Wilson solution, here is my try:

    def to_time
      #Convert a fraction of a day to a number of microseconds
      usec = (sec_fraction * 60 * 60 * 24 * (10**6)).to_i
      t = Time.gm(year, month, day, hour, min, sec, usec)
      t - offset.abs.div(SECONDS_IN_DAY)
    end
    

    You'll get the same time in UTC, loosing the timezone (unfortunately)

    Also, if you have ruby 1.9, just try the to_time method

提交回复
热议问题