且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Ruby 中转换为/从日期时间和时间

更新时间:2023-02-03 15:31:58

您将需要两个略有不同的转换.

You'll need two slightly different conversions.

要将 Time 转换为 DateTime,您可以按如下方式修改 Time 类:

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

对日期的类似调整将使您可以将 DateTime 转换为 Time .

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.他们的代码重用 policy 允许这样做.

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