Skip to content

Instantly share code, notes, and snippets.

@bdewater
Created June 8, 2020 16:07
Show Gist options
  • Save bdewater/4c483beb7f521841a915f62c56fdcea4 to your computer and use it in GitHub Desktop.
Save bdewater/4c483beb7f521841a915f62c56fdcea4 to your computer and use it in GitHub Desktop.
Ruby Time vs DateTime
# From https://gist.github.com/pixeltrix/e2298822dd89d854444b / https://ruby-doc.org/stdlib-2.3.0/libdoc/date/rdoc/DateTime.html
# "Almost certainly you'll want to use Time since your app is probably dealing with current dates and times."
# Here's a practical example
require "time"
# The line below is probably set different for your system, or not at all
# On macOS I can see this with `sudo systemsetup -gettimezone`
# I'm in Montreal so for the examples to work you need to pretend to be as well
ENV["TZ"] = "America/Toronto"
time = Time.parse("2018-03-11 1:00:00")
# => 2018-03-11 01:00:00 -0500
time.dst?
# => false
summer_time = time + 60*60 # advance one hour
# => 2018-03-11 03:00:00 -0400
summer_time.dst?
# => true
datetime = DateTime.parse "2018-03-11 1:00:00 -05:00"
# => #<DateTime: 2018-03-11T01:00:00-05:00 ((2458189j,21600s,0n),-18000s,2299161j)>
datetime.dst? # NoMethodError: undefined method `dst?' for #<DateTime:0x00007fbc2010c258>
summer_datetime = datetime + (1.0/24) # advanced one hour
# => #<DateTime: 2018-03-11T02:00:00-05:00 ((2458189j,25200s,0n),-18000s,2299161j)>
# UTC offset wise this is Jamaica instead of Montreal
summer_time.to_datetime # same time, 1 hour different UTC offsets
# => #<DateTime: 2018-03-11T03:00:00-04:00 ((2458189j,25200s,0n),-14400s,2299161j)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment