Joël Quenneville
November 14, 2023
200

Which Time Is It?

Can you add two time values together? Yes. No. Not so fast!

Reset your clocks and join me on a graphical tour of time itself. You'll discover how "time" is more than a single thing, build intuition around what different operations mean, and get a sense of when some operations are nonsensical. You'll leave with a better mental model for thinking about time and avoiding subtle time-related bugs in your own code.

Originally given at RubyConf 2023

Joël Quenneville

November 14, 2023

Transcript

5. Two Kinds of Time Moment November 14th, 2023 at 10:30AM

PST Duration 45 minutes

18. Resolution impacts enumeration start = Date.new(2023, 11, 12) finish =

Date.new(2023, 11, 15) (start..finish).map(&:to_s) # 2023-11-12 # 2023-11-13 # 2023-11-14 # 2023-11015

time with

24. time + numeric -> time Notice: We can't add two

time instances!

ASKING:

float

ASKING:
32. time - numeric -> time What point is 45 mins

before point A?

points!

35. How big is the duration between points A and B?

SUBTRACTION IS ASKING:
36. time - time -> float What is the distance between

points A and B?

38. Same equation, rearanged point1 + duration = point2 (Time#+) point2

- duration = point1 (Time#- v1) point2 - point1 = duration (Time#- v2)

40. Other Kinds of Time Moment November 14th, 2023 at 11:30AM

PST Duration 45 minutes Time of Day 5:30 PM

61. Common Implementations UNIX Time milliseconds since Jan 1, 1970 Postgres

Time of Day microseconds since midnight Ruby Date days since Jan 1, 4713 BCE
62. Just a big counter class TimeOfDay def initialize(microseconds_since_midnight) @counter =

(microseconconds_since_midnight % MS_PER_DAY) end end
63. Custom constructor class TimeOfDay def self.from_parts(hours:, minutes:, seconds:) total =

(hours * MICROSECONDS_PER_HOUR) + (minutes * MICROSECONDS_PER_MINUTE) + (seconds * MICROSECONDS_PER_SECOND) new(total) end end

66. When working with time Think About What kind of time

you need moment, duration, tod, etc What operations make sense (and which ones don't!) both within and across types What resolution you need e.g. Time vs Date class