在 Ruby 中转换为/从日期时间和时间 [英] Convert to/from DateTime and Time in Ruby
本文介绍了在 Ruby 中转换为/从日期时间和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Ruby 中在 DateTime 和 Time 对象之间进行转换?
How do you convert between a DateTime and a Time object in Ruby?
推荐答案
您将需要两个略有不同的转换.
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.
这篇关于在 Ruby 中转换为/从日期时间和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文