SlideShare a Scribd company logo
1 of 34
Fun Times
(and DateTimes and Dates and zones)
in Ruby
OR: Accurate Times At Railsmont High
OR: UTC and You and Me
Times, time zones, times without dates,
and other Ruby and Rails techniques
Hi, I’m Geoff
I’m the co-founder at Cortex
http://cortexintel.com
Best label maker use ever
Why is time important?
Track when something happened
• Jane signed in at 4:12pm
• Meter reading for interval starting at 6:45am
Schedule when something will happen
• Send an email at 8:00am
• Check for new users every hour on the hour
Why is time hard?
Why is time hard?
• Daylight savings and “summer time”
• Time zones change over time
• Displaying times differently for users based on
their locale
• Caching makes it hard to show times relative to
“now”
What is UTC?
“Coordinated Universal Time”
International Standard
Other time zones can be described with the
number of hours and minutes with which they
deviate from UTC as an offset
Everywhere a different time
UTC Offsets
Offsets are defined as “+/- hh:mm”
As of 7:30pm in Washington, DC on March 5th, here are
some offsets:
• DC: -05:00
• SF: -08:00
• London: +00:00 (London is UTC during the winter)
• Bangalore: +05:30 (not always round hours!)
Why use UTC?
Why use UTC?
In the database:
• UTC always moves forward
• No need to consider DST when calculating
distance between two times
• Time zones change over time!*
Why use UTC?
Outside the database:
• Avoid confusion over what zone you are in
• Easy to convert back to local time just before
you render (after manipulation or querying is
done)
• UTC is useful for cached pages and partials
Time Zones
Rails uses the tzinfo gem, which tracks the IANA
list of official time zones
ActiveSupport::TimeZone.all gives you a list of all
allowed time zones. They are named on a
region/city basis in most cases:
“America/New_York”, “Asia/Tokyo”,
“Africa/Khartoum”, etc.
Avoid Date.today
Date.today uses the server time zone
Use Time.now.in_time_zone(time_zone).to_date
to get the real date from the user’s perspective
ActiveSupport’s Time.current will always give you
UTC if you’ve set your default time zone to UTC
(Time.now will use the server time zone)
If you need to parse times in a local reference,
wrap it in a `Time.use_zone` block (more later)
Time vs. DateTime
• Previously, Time used to be bounded, and couldn’t
represent dates before 1970 or far in the future
• DateTime does not consider leap seconds or track
summer time rules (daylight savings)
• In Ruby (except for 1.9.3), Time, built in C, appears
to be faster in most cases
• Now that Ruby 2.0 supports unbounded Time, use it
whenever possible to avoid confusion
Ruby Tips
Just use UTC.
Everyone thinks their app won’t need to worry
about time zones. You will regret it later if you
don’t follow this rule.
# config/application.rb
# Set time zone
config.active_record.default_time_zone = “UTC”
ActiveRecord types
• date stores a date with no time information,
“2015-03-05”
• datetime stores a timestamp, or a fixed point in
time: “2015-03-06 00:30:00”
• time stores a time of day with no tie to a specific
date “09:00:00”
Times without dates
ActiveRecord times
Be careful when using time attributes for times
without dates! ActiveRecord returns time
attributes as UTC times on 1/1/2000.
# user’s time zone is “America/New_York”
messaging_preferences.update!(morning_update_time: “07:00”)
messaging_preferences.morning_update_time
=> 2000-01-01 07:00:00 UTC
Fix it everywhere
class TimeWithoutDateToTime
def initialize(undated_time, date, time_zone)
@undated_time = undated_time
@date = date
@time_zone = time_zone
end
def time
date.in_time_zone(time_zone).change(
hour: hour,
min: min,
sec: sec
)
end
protected
attr_reader :date, :time_zone, :undated_time
private
delegate :hour, :min, :sec, to: :undated_time
end
Schema best practices
• Name database columns that store times with
the suffix “_at”, such as “signed_up_at”
• Name database columns that store dates with
the suffix “_on”, such as “joined_on”
• Name database columns that store times not
tied to a particular date with the suffix “_time”,
such as “morning_update_scheduled_time”
PostgreSQL
http://www.postgresql.org/docs/9.1/static/functions
-datetime.html
Check out PostgreSQL’s documentation on
date/time functions.
SELECT * FROM measurements
WHERE measured_at
AT TIME ZONE ‘UTC’
AT TIME ZONE ‘America/New_York’
BETWEEN x and y
Taking User Input
Users expect to be able to specify times in their
own time zone.
Solution: process user input with an around block
and Time.use_zone. Create times in the block
with Time.zone.local.
User Input Example
around_filter :set_user_time_zone
protected
# be sure to use Time.zone.local rather than
# Time.new to instantiate any time objects in
# the block that are in the user’s time zone
def set_user_time_zone
Time.use_zone(current_user.time_zone) { yield }
end
JavaScript
Use Moment.js and Moment-Timezone
• Convenient, ActiveSupport-like methods for
manipulation
• Much better query and display methods than
JS-native Date objects
• Locale-based timezones
Parsing time
Parsing time
Chronic (mojombo/chronic) provides natural language
parsing for times in Ruby
Chronic.parse("last Saturday”)
Use it over Time.parse when you need to take in a
string from an external source and turn it into a time
(even strings you suspect are properly formatted)
Testing
Testing Tools
• Timecop
https://github.com/travisjeffery/timecop
Freeze time at any point, travel to any time
• Zonebie
https://github.com/alindeman/zonebie
Changes your app’s timezone to help find bugs
related to times and zones
Guidelines for testing
• Any time your test depends on the relation of some
time to “now”, always use Timecop to freeze the
time
• Use Timecop to travel between times when testing
scenarios where time elapses
• Test around times where your local time is likely to
be a different date than UTC
• Only change the local time zone in a test with an
“around” block to prevent leaks into other tests
Caching
• For pages or partials that will be cached, don’t
display relative time using Rails view helpers.
Instead, render the moment as a fixed time in a
default time zone
• Store the time on the HTML tag as an attribute:
<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>
• Use the JS timeago library (timeago.yarp.com)
to re-render timestamp tags as relative times
Questions?
Further Reading
• Joel Olivera’s awesome Boston.rb talk:
http://bit.ly/1AYs6Or
• Ruby Time API:
http://ruby-doc.org//core-2.2.0/Time.html
• Rails TimeWithZone API:
http://apidock.com/rails/ActiveSupport/TimeWithZone
• SvN (37signals/Basecamp) on caching and JS
reformatting: https://signalvnoise.com/posts/1557-
javascript-makes-relative-times-compatible-with-caching
Thanks!
I love talking about Ruby and Rails, so feel free to
reach out to me with questions!
email: geoff@fivetool.io
Github: geoffharcourt
Twitter: @geoffharcourt

More Related Content

What's hot

Docker and Fluentd
Docker and FluentdDocker and Fluentd
Docker and FluentdN Masahiro
 
AWS Cloud experience concepts tips and tricks
AWS Cloud experience concepts tips and tricksAWS Cloud experience concepts tips and tricks
AWS Cloud experience concepts tips and tricksDirk Harms-Merbitz
 
Technologies, Data Analytics Service and Enterprise Business
Technologies, Data Analytics Service and Enterprise BusinessTechnologies, Data Analytics Service and Enterprise Business
Technologies, Data Analytics Service and Enterprise BusinessSATOSHI TAGOMORI
 
Rails performance at Justin.tv - Guillaume Luccisano
Rails performance at Justin.tv - Guillaume LuccisanoRails performance at Justin.tv - Guillaume Luccisano
Rails performance at Justin.tv - Guillaume LuccisanoGuillaume Luccisano
 
Terraform Best Practices - DevOps Unicorns 2019
Terraform Best Practices - DevOps Unicorns 2019Terraform Best Practices - DevOps Unicorns 2019
Terraform Best Practices - DevOps Unicorns 2019Anton Babenko
 
Integrating Apache Pulsar with Big Data Ecosystem
Integrating Apache Pulsar with Big Data EcosystemIntegrating Apache Pulsar with Big Data Ecosystem
Integrating Apache Pulsar with Big Data EcosystemStreamNative
 
Messaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkMessaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkTomas Doran
 
A Unified Platform for Real-time Storage and Processing
A Unified Platform for Real-time Storage and ProcessingA Unified Platform for Real-time Storage and Processing
A Unified Platform for Real-time Storage and ProcessingStreamNative
 
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/Sec
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/SecNetflix Keystone - How Netflix Handles Data Streams up to 11M Events/Sec
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/SecPeter Bakas
 
Slide #1:Introduction to Apache Storm
Slide #1:Introduction to Apache StormSlide #1:Introduction to Apache Storm
Slide #1:Introduction to Apache StormMd. Shamsur Rahim
 
Deploying Kafka at Dropbox, Mark Smith, Sean Fellows
Deploying Kafka at Dropbox, Mark Smith, Sean FellowsDeploying Kafka at Dropbox, Mark Smith, Sean Fellows
Deploying Kafka at Dropbox, Mark Smith, Sean Fellowsconfluent
 
Docker and Pharo @ZWEIDENKER
Docker and Pharo @ZWEIDENKERDocker and Pharo @ZWEIDENKER
Docker and Pharo @ZWEIDENKERZWEIDENKER GmbH
 
Distributed Systems explained (with NodeJS) - Bruno Bossola, JUG Torino
Distributed Systems explained (with NodeJS) - Bruno Bossola, JUG TorinoDistributed Systems explained (with NodeJS) - Bruno Bossola, JUG Torino
Distributed Systems explained (with NodeJS) - Bruno Bossola, JUG TorinoCodemotion Tel Aviv
 
Terraform Architech
Terraform ArchitechTerraform Architech
Terraform ArchitechDavid Hsu
 

What's hot (20)

Serverless by examples and case studies
Serverless by examples and case studiesServerless by examples and case studies
Serverless by examples and case studies
 
Docker and Fluentd
Docker and FluentdDocker and Fluentd
Docker and Fluentd
 
Apache pulsar
Apache pulsarApache pulsar
Apache pulsar
 
AWS Cloud experience concepts tips and tricks
AWS Cloud experience concepts tips and tricksAWS Cloud experience concepts tips and tricks
AWS Cloud experience concepts tips and tricks
 
Technologies, Data Analytics Service and Enterprise Business
Technologies, Data Analytics Service and Enterprise BusinessTechnologies, Data Analytics Service and Enterprise Business
Technologies, Data Analytics Service and Enterprise Business
 
Rails performance at Justin.tv - Guillaume Luccisano
Rails performance at Justin.tv - Guillaume LuccisanoRails performance at Justin.tv - Guillaume Luccisano
Rails performance at Justin.tv - Guillaume Luccisano
 
Terraform Best Practices - DevOps Unicorns 2019
Terraform Best Practices - DevOps Unicorns 2019Terraform Best Practices - DevOps Unicorns 2019
Terraform Best Practices - DevOps Unicorns 2019
 
Integrating Apache Pulsar with Big Data Ecosystem
Integrating Apache Pulsar with Big Data EcosystemIntegrating Apache Pulsar with Big Data Ecosystem
Integrating Apache Pulsar with Big Data Ecosystem
 
Messaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkMessaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new framework
 
A Unified Platform for Real-time Storage and Processing
A Unified Platform for Real-time Storage and ProcessingA Unified Platform for Real-time Storage and Processing
A Unified Platform for Real-time Storage and Processing
 
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/Sec
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/SecNetflix Keystone - How Netflix Handles Data Streams up to 11M Events/Sec
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/Sec
 
Apache Storm
Apache StormApache Storm
Apache Storm
 
Slide #1:Introduction to Apache Storm
Slide #1:Introduction to Apache StormSlide #1:Introduction to Apache Storm
Slide #1:Introduction to Apache Storm
 
Apache Storm Internals
Apache Storm InternalsApache Storm Internals
Apache Storm Internals
 
NoSql
NoSqlNoSql
NoSql
 
Deploying Kafka at Dropbox, Mark Smith, Sean Fellows
Deploying Kafka at Dropbox, Mark Smith, Sean FellowsDeploying Kafka at Dropbox, Mark Smith, Sean Fellows
Deploying Kafka at Dropbox, Mark Smith, Sean Fellows
 
Docker and Pharo @ZWEIDENKER
Docker and Pharo @ZWEIDENKERDocker and Pharo @ZWEIDENKER
Docker and Pharo @ZWEIDENKER
 
Distributed Systems explained (with NodeJS) - Bruno Bossola, JUG Torino
Distributed Systems explained (with NodeJS) - Bruno Bossola, JUG TorinoDistributed Systems explained (with NodeJS) - Bruno Bossola, JUG Torino
Distributed Systems explained (with NodeJS) - Bruno Bossola, JUG Torino
 
Terraform @Base
Terraform @BaseTerraform @Base
Terraform @Base
 
Terraform Architech
Terraform ArchitechTerraform Architech
Terraform Architech
 

Similar to Fun times with ruby

Date and Time Odds Ends Oddities
Date and Time Odds Ends OdditiesDate and Time Odds Ends Oddities
Date and Time Odds Ends OdditiesMaggie Pint
 
"Working with date and time data in .NET", Jon Skeet
"Working with date and time data in .NET", Jon Skeet"Working with date and time data in .NET", Jon Skeet
"Working with date and time data in .NET", Jon SkeetFwdays
 
Lesson 05 - Time in Distrributed System.pptx
Lesson 05 - Time in Distrributed System.pptxLesson 05 - Time in Distrributed System.pptx
Lesson 05 - Time in Distrributed System.pptxLagamaPasala
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4Kenji HASUNUMA
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3Kenji HASUNUMA
 
Date and Time MomentJS Edition
Date and Time MomentJS EditionDate and Time MomentJS Edition
Date and Time MomentJS EditionMaggie Pint
 
That Conference Date and Time
That Conference Date and TimeThat Conference Date and Time
That Conference Date and TimeMaggie Pint
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4Kenji HASUNUMA
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3Kenji HASUNUMA
 
A JSR-310 Date: Beyond JODA Time
A JSR-310 Date: Beyond JODA TimeA JSR-310 Date: Beyond JODA Time
A JSR-310 Date: Beyond JODA TimeDaniel Sobral
 
#PDR15 - Best Use Cases For Timeline
#PDR15 - Best Use Cases For Timeline#PDR15 - Best Use Cases For Timeline
#PDR15 - Best Use Cases For TimelinePebble Technology
 
Java 8 date & time javaday2014
Java 8 date & time javaday2014Java 8 date & time javaday2014
Java 8 date & time javaday2014Oleg Tsal-Tsalko
 
The State of Time in OpenHistoricalMap
The State of Time in OpenHistoricalMapThe State of Time in OpenHistoricalMap
The State of Time in OpenHistoricalMapnfgusedautoparts
 
Average Active Sessions - OaktableWorld 2013
Average Active Sessions - OaktableWorld 2013Average Active Sessions - OaktableWorld 2013
Average Active Sessions - OaktableWorld 2013John Beresniewicz
 
Update of time-invalid information in knowledge bases through mobile agents
Update of time-invalid information in knowledge bases through mobile agentsUpdate of time-invalid information in knowledge bases through mobile agents
Update of time-invalid information in knowledge bases through mobile agentsVrije Universiteit Amsterdam
 
Data Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing ItData Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing Itkanaugust
 

Similar to Fun times with ruby (20)

Date and Time Odds Ends Oddities
Date and Time Odds Ends OdditiesDate and Time Odds Ends Oddities
Date and Time Odds Ends Oddities
 
"Working with date and time data in .NET", Jon Skeet
"Working with date and time data in .NET", Jon Skeet"Working with date and time data in .NET", Jon Skeet
"Working with date and time data in .NET", Jon Skeet
 
Lesson 05 - Time in Distrributed System.pptx
Lesson 05 - Time in Distrributed System.pptxLesson 05 - Time in Distrributed System.pptx
Lesson 05 - Time in Distrributed System.pptx
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3
 
Date and Time MomentJS Edition
Date and Time MomentJS EditionDate and Time MomentJS Edition
Date and Time MomentJS Edition
 
That Conference Date and Time
That Conference Date and TimeThat Conference Date and Time
That Conference Date and Time
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3
 
A JSR-310 Date: Beyond JODA Time
A JSR-310 Date: Beyond JODA TimeA JSR-310 Date: Beyond JODA Time
A JSR-310 Date: Beyond JODA Time
 
Java 8 date & time api
Java 8 date & time apiJava 8 date & time api
Java 8 date & time api
 
#PDR15 - Best Use Cases For Timeline
#PDR15 - Best Use Cases For Timeline#PDR15 - Best Use Cases For Timeline
#PDR15 - Best Use Cases For Timeline
 
Java 8 date & time javaday2014
Java 8 date & time javaday2014Java 8 date & time javaday2014
Java 8 date & time javaday2014
 
High Performance Solr
High Performance SolrHigh Performance Solr
High Performance Solr
 
The State of Time in OpenHistoricalMap
The State of Time in OpenHistoricalMapThe State of Time in OpenHistoricalMap
The State of Time in OpenHistoricalMap
 
Average Active Sessions - OaktableWorld 2013
Average Active Sessions - OaktableWorld 2013Average Active Sessions - OaktableWorld 2013
Average Active Sessions - OaktableWorld 2013
 
Update of time-invalid information in knowledge bases through mobile agents
Update of time-invalid information in knowledge bases through mobile agentsUpdate of time-invalid information in knowledge bases through mobile agents
Update of time-invalid information in knowledge bases through mobile agents
 
Java 8
Java 8Java 8
Java 8
 
Data Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing ItData Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing It
 
Timezone Mess
Timezone MessTimezone Mess
Timezone Mess
 

Recently uploaded

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Recently uploaded (20)

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Fun times with ruby

  • 1. Fun Times (and DateTimes and Dates and zones) in Ruby OR: Accurate Times At Railsmont High OR: UTC and You and Me Times, time zones, times without dates, and other Ruby and Rails techniques
  • 2. Hi, I’m Geoff I’m the co-founder at Cortex http://cortexintel.com
  • 3. Best label maker use ever
  • 4. Why is time important? Track when something happened • Jane signed in at 4:12pm • Meter reading for interval starting at 6:45am Schedule when something will happen • Send an email at 8:00am • Check for new users every hour on the hour
  • 5. Why is time hard?
  • 6. Why is time hard? • Daylight savings and “summer time” • Time zones change over time • Displaying times differently for users based on their locale • Caching makes it hard to show times relative to “now”
  • 7. What is UTC? “Coordinated Universal Time” International Standard Other time zones can be described with the number of hours and minutes with which they deviate from UTC as an offset
  • 9. UTC Offsets Offsets are defined as “+/- hh:mm” As of 7:30pm in Washington, DC on March 5th, here are some offsets: • DC: -05:00 • SF: -08:00 • London: +00:00 (London is UTC during the winter) • Bangalore: +05:30 (not always round hours!)
  • 11. Why use UTC? In the database: • UTC always moves forward • No need to consider DST when calculating distance between two times • Time zones change over time!*
  • 12. Why use UTC? Outside the database: • Avoid confusion over what zone you are in • Easy to convert back to local time just before you render (after manipulation or querying is done) • UTC is useful for cached pages and partials
  • 13. Time Zones Rails uses the tzinfo gem, which tracks the IANA list of official time zones ActiveSupport::TimeZone.all gives you a list of all allowed time zones. They are named on a region/city basis in most cases: “America/New_York”, “Asia/Tokyo”, “Africa/Khartoum”, etc.
  • 14. Avoid Date.today Date.today uses the server time zone Use Time.now.in_time_zone(time_zone).to_date to get the real date from the user’s perspective ActiveSupport’s Time.current will always give you UTC if you’ve set your default time zone to UTC (Time.now will use the server time zone) If you need to parse times in a local reference, wrap it in a `Time.use_zone` block (more later)
  • 15. Time vs. DateTime • Previously, Time used to be bounded, and couldn’t represent dates before 1970 or far in the future • DateTime does not consider leap seconds or track summer time rules (daylight savings) • In Ruby (except for 1.9.3), Time, built in C, appears to be faster in most cases • Now that Ruby 2.0 supports unbounded Time, use it whenever possible to avoid confusion
  • 16. Ruby Tips Just use UTC. Everyone thinks their app won’t need to worry about time zones. You will regret it later if you don’t follow this rule. # config/application.rb # Set time zone config.active_record.default_time_zone = “UTC”
  • 17. ActiveRecord types • date stores a date with no time information, “2015-03-05” • datetime stores a timestamp, or a fixed point in time: “2015-03-06 00:30:00” • time stores a time of day with no tie to a specific date “09:00:00”
  • 19. ActiveRecord times Be careful when using time attributes for times without dates! ActiveRecord returns time attributes as UTC times on 1/1/2000. # user’s time zone is “America/New_York” messaging_preferences.update!(morning_update_time: “07:00”) messaging_preferences.morning_update_time => 2000-01-01 07:00:00 UTC
  • 20. Fix it everywhere class TimeWithoutDateToTime def initialize(undated_time, date, time_zone) @undated_time = undated_time @date = date @time_zone = time_zone end def time date.in_time_zone(time_zone).change( hour: hour, min: min, sec: sec ) end protected attr_reader :date, :time_zone, :undated_time private delegate :hour, :min, :sec, to: :undated_time end
  • 21. Schema best practices • Name database columns that store times with the suffix “_at”, such as “signed_up_at” • Name database columns that store dates with the suffix “_on”, such as “joined_on” • Name database columns that store times not tied to a particular date with the suffix “_time”, such as “morning_update_scheduled_time”
  • 22. PostgreSQL http://www.postgresql.org/docs/9.1/static/functions -datetime.html Check out PostgreSQL’s documentation on date/time functions. SELECT * FROM measurements WHERE measured_at AT TIME ZONE ‘UTC’ AT TIME ZONE ‘America/New_York’ BETWEEN x and y
  • 23. Taking User Input Users expect to be able to specify times in their own time zone. Solution: process user input with an around block and Time.use_zone. Create times in the block with Time.zone.local.
  • 24. User Input Example around_filter :set_user_time_zone protected # be sure to use Time.zone.local rather than # Time.new to instantiate any time objects in # the block that are in the user’s time zone def set_user_time_zone Time.use_zone(current_user.time_zone) { yield } end
  • 25. JavaScript Use Moment.js and Moment-Timezone • Convenient, ActiveSupport-like methods for manipulation • Much better query and display methods than JS-native Date objects • Locale-based timezones
  • 27. Parsing time Chronic (mojombo/chronic) provides natural language parsing for times in Ruby Chronic.parse("last Saturday”) Use it over Time.parse when you need to take in a string from an external source and turn it into a time (even strings you suspect are properly formatted)
  • 29. Testing Tools • Timecop https://github.com/travisjeffery/timecop Freeze time at any point, travel to any time • Zonebie https://github.com/alindeman/zonebie Changes your app’s timezone to help find bugs related to times and zones
  • 30. Guidelines for testing • Any time your test depends on the relation of some time to “now”, always use Timecop to freeze the time • Use Timecop to travel between times when testing scenarios where time elapses • Test around times where your local time is likely to be a different date than UTC • Only change the local time zone in a test with an “around” block to prevent leaks into other tests
  • 31. Caching • For pages or partials that will be cached, don’t display relative time using Rails view helpers. Instead, render the moment as a fixed time in a default time zone • Store the time on the HTML tag as an attribute: <abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr> • Use the JS timeago library (timeago.yarp.com) to re-render timestamp tags as relative times
  • 33. Further Reading • Joel Olivera’s awesome Boston.rb talk: http://bit.ly/1AYs6Or • Ruby Time API: http://ruby-doc.org//core-2.2.0/Time.html • Rails TimeWithZone API: http://apidock.com/rails/ActiveSupport/TimeWithZone • SvN (37signals/Basecamp) on caching and JS reformatting: https://signalvnoise.com/posts/1557- javascript-makes-relative-times-compatible-with-caching
  • 34. Thanks! I love talking about Ruby and Rails, so feel free to reach out to me with questions! email: geoff@fivetool.io Github: geoffharcourt Twitter: @geoffharcourt

Editor's Notes

  1. In 2011, Russia ended use of DST time US regions have changed DST policies over time TZ regions have merged and divided
  2. In 2011, Russia ended use of DST time US regions have changed DST policies over time TZ regions have merged and divided
  3. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  4. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  5. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  6. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  7. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  8. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  9. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  10. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  11. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  12. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  13. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time
  14. ActiveRecord and ActiveSupport don’t help much here, as when you pull a timestamp at the console you often get it in local time