在Ruby中转换为/从DateTime和Time [英] Convert to/from DateTime and Time in Ruby

查看:99
本文介绍了在Ruby中转换为/从DateTime和Time的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Ruby中的DateTime和Time对象之间进行转换?

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

推荐答案

您需要两个稍微不同的转换

You'll need two slightly different conversions.

要从时间转换为 DateTime 修改时间类如下:

To convert from Time to DateTime you can amend the Time class as follows:

require 'date'
class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end

Date类似的调整将让您将 DateTime 转换为时间

Similar adjustments to Date will let you convert DateTime to Time .

class Date
  def to_gm_time
    to_time(new_offset, :gm)
  end

  def to_local_time
    to_time(new_offset(DateTime.now.offset-offset), :local)
  end

  private
  def to_time(dest, method)
    #Convert a fraction of a day to a number of microseconds
    usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
    Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
              dest.sec, usec)
  end
end

请注意,您必须在当地时间和GM之间进行选择/ UTC时间。

Note that you have to choose between local time and GM/UTC time.

上述代码段均取自O'Reilly的 Ruby Cookbook 。他们的代码重用政策允许这一点。

Both the above code snippets are taken from O'Reilly's Ruby Cookbook. Their code reuse policy permits this.

这篇关于在Ruby中转换为/从DateTime和Time的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆