Rails' ActiveSupport module extends the builtin ruby Time class with a number of methods.
Notably, there is the to_formatted_s
method, which lets you write Time.now.to_formatted_s(:db)
to get a string in Database format, rather than having to write ugly strftime
format-strings everywhere.
My question is, is there a way to go backwards?
Something like Time.parse_formatted_s(:db)
which would parse a string in Database format, returning a new Time object. This seems like something that rails should be providing, but if it is, I can't find it.
Am I just not able to find it, or do I need to write it myself?
Thanks
Rails 5 finally provides
strptime
!Works great unless your date is in some weird format.
It looks like ActiveSupport does provide the parsing methods you are looking for (and I was looking for too), after all! — at least if the string you are trying to parse is a standard, ISO-8601-formatted (
:db
format) date.If the date you're trying to parse is already in your local time zone, it's really easy!
and that time-zone-aware time can then easily be converted to UTC
or to other time zones:
If the date string you're trying to parse is in UTC, on the other hand, it doesn't look like there's any method to parse it directly into a TimeWithZone, but I was able to work around that be first using DateTime.strptime...
If the date you're trying to parse is in UTC and you want it to stay as UTC, you can use:
If the date you're trying to parse is in UTC and you want it converted to your default time zone, you can use:
It looks like it can even parse other formats, such as the strange format that Time#to_s produces:
I'm quite impressed.
Here are some more examples from [http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html][1]:
More documentation links for reference:
I just ran into this as well and none of the above answers were satisfactory to me. Ideally one could use
ActiveSupport::TimeZone
just likeTime
and call.strptime
on it with any arbitrary format and get back the correctTimeZone
object.ActiveSupport::TimeZone.strptime
doesn't exist so I created this monkeypatch: