So when should you use DateTime in Ruby and when should you use Time? Almost certainly you'll want to use Time since your app is probably dealing with current dates and times. However, if you need to deal with dates and times in a historical context you'll want to use DateTime to avoid making the same mistakes as UNESCO.
Last active
May 3, 2017 01:39
-
-
Save Domon/80aaab465841c67057ad3d3bc8f954c6 to your computer and use it in GitHub Desktop.
Time vs DateTime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
require 'date' | |
Benchmark.bm do |bm| | |
bm.report('DateTime:') do | |
1_000_000.times { DateTime.now } | |
end | |
bm.report('Time: ') do | |
1_000_000.times { Time.now } | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ruby time_vs_datetime.rb | |
user system total real | |
DateTime: 0.820000 0.010000 0.830000 ( 0.824737) | |
Time: 0.410000 0.000000 0.410000 ( 0.415594) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'time' | |
p DateTime.now.zone | |
p Time.now.zone | |
time = '2016-09-04 11:10:14.495219' | |
p DateTime.parse(time).zone | |
p Time.parse(time).zone |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ruby time_vs_datetime_parse.rb | |
"+10:00" | |
"AEST" | |
"+00:00" | |
"AEST" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment