Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Which Time Is It?

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
Tweet

More Decks by Joël Quenneville

Other Decks in Technology

Transcript

  1. 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
  2. Same equation, rearanged point1 + duration = point2 (Time#+) point2

    - duration = point1 (Time#- v1) point2 - point1 = duration (Time#- v2)
  3. Other Kinds of Time Moment November 14th, 2023 at 11:30AM

    PST Duration 45 minutes Time of Day 5:30 PM
  4. Common Implementations UNIX Time milliseconds since Jan 1, 1970 Postgres

    Time of Day microseconds since midnight Ruby Date days since Jan 1, 4713 BCE
  5. 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
  6. 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