Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which should I always parse date times with? DateTime, Time, Time.zone?

In Rails, I see I have a few options to parse a date and a date-time. What is the best practice for parsing dates for the sole purpose of persisting them into the DB via ActiveRecord? And why?

Time.zone.parse(...)
Time.parse(...)
DateTime.parse(...)
like image 731
Ron Garrity Avatar asked May 10 '12 01:05

Ron Garrity


People also ask

What is parse date time?

Date.parse() The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

Does C# DateTime have a timezone?

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means. DateTimeOffset is somewhat better - that's basically a UTC time and an offset.


1 Answers

Go with Time.zone.parse if you just want to write into ActiveRecord.

DateTime should be avoided. If you're handling dates, you should use Date.parse instead.

Beyond that, it depends on whether the input comes with timezone information, what the current timezone is set to, and whether you want timezones in your data.

Time.zone.parse will return an ActiveSupport::TimeWithZone, defaulting to UTC.

> Time.zone.parse("12:30")
=> Thu, 10 May 2012 12:30:00 UTC +00:00 

Time.parse will return a Time, with a zone if it's specified in the input, or the local TZ.

> Time.parse("12:30")
=> 2012-05-09 12:30:00 -0700 

For a more detailed explanation of Ruby time comparisons and precision, read this blog post:

http://blog.solanolabs.com/rails-time-comparisons-devil-details-etc/

like image 105
Jay Moorthi Avatar answered Sep 23 '22 02:09

Jay Moorthi