How do you convert between a DateTime and a Time object in Ruby?
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- How to account for clock offsets in a distributed
相关文章
- Ruby using wrong version of openssl
- How to truncate seconds in TSQL?
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- How to remove seconds from datetime?
- Segmentation fault with ruby 2.0.0p247 leading to
- OLS with pandas: datetime index as predictor
Unfortunately, the
DateTime.to_time, Time.to_datetime
andTime.parse
functions don't retain the timezone info. Everything is converted to local timezone during conversion. Date arithmetics still work but you won't be able to display the dates with their original timezones. That context information is often important. For example, if I want to see transactions performed during business hours in New York I probably prefer to see them displayed in their original timezones, not my local timezone in Australia (which 12 hrs ahead of New York).The conversion methods below do keep that tz info.
For Ruby 1.8, look at Gordon Wilson's answer. It's from the good old reliable Ruby Cookbook.
For Ruby 1.9, it's slightly easier.
This prints the following
The full original DateTime info including timezone is kept.
As an update to the state of the Ruby ecosystem,
Date
,DateTime
andTime
now have methods to convert between the various classes. Using Ruby 1.9.2+:Improving on Gordon Wilson solution, here is my try:
You'll get the same time in UTC, loosing the timezone (unfortunately)
Also, if you have ruby 1.9, just try the
to_time
methodYou'll need two slightly different conversions.
To convert from
Time
toDateTime
you can amend the Time class as follows:Similar adjustments to Date will let you convert
DateTime
toTime
.Note that you have to choose between local time and GM/UTC time.
Both the above code snippets are taken from O'Reilly's Ruby Cookbook. Their code reuse policy permits this.