Created
March 13, 2018 10:15
-
-
Save mroach/3346dbb00648e2a962a21ad68f60c51f to your computer and use it in GitHub Desktop.
DateTime and Time math
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
# When adding or subtracting DateTime objects, the return type is a Rational expressing the fraction of a day's number of minutes (1440). So 0.5 would mean half a day, or 720 minutes, or 12 hours. | |
# When adding or subtracting Time objects, the return type is Float expressing the difference in seconds. | |
#Here's an example showing the difference between two times that are an hour apart: | |
MINUTES_IN_A_DAY = 1440 | |
ref1 = "2018-03-13T08:00:00+00:00" | |
ref2 = "2018-03-13T09:00:00+00:00" | |
# -3600 = 3600 seconds ago, i.e. 1 hour ago | |
Time.zone.iso8601(ref1) - Time.zone.iso8601(ref2) | |
# => -3600.0 | |
# You'd get the same result if you did 60.0 / 1440.0 | |
DateTime.iso8601(ref1) - DateTime.iso8601(ref2) | |
# => (-1/24) | |
# Shown another way, convert to float and multiply by 1440 minutes to get | |
# difference in minutes | |
(DateTime.iso8601(ref1) - DateTime.iso8601(ref2)).to_f * MINUTES_IN_A_DAY | |
# => -60.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment