Time Helpers You Might Not Know

In Ruby on Rails, there are a number of time helpers that can be used to format and manipulate dates and times. We selected a few ones you might not know that can be used to make your code more readable and to provide a better user experience.

Instead of:

1
created_at < Time.current

Use this:

1
2
created_at.before?(Time.current)
created_at.past?

Instead of

1
created_at > Time.current

Use this:

1
2
created_at.after?(Time.current)
created_at.future?
1
2
Time.current.all_day
=> Mon, 11 Mar 2024 00:00:00 UTC +00:00..Mon, 11 Mar 2024 23:59:59 UTC +00:00
1
2
Time.current.all_week
=> Mon, 11 Mar 2024 00:00:00 UTC +00:00..Sun, 17 Mar 2024 23:59:59 UTC +00:00
1
2
Time.current.all_month
=> Fri, 01 Mar 2024 00:00:00 UTC +00:00..Sun, 31 Mar 2024 23:59:59 UTC +00:00
1
2
3
# Returns the time after tomorrow
tomorrow = (Time.now + 1.day)
=> 2023-12-31 16:05:11 +0000
1
2
3
# Returns the time formatted as "HH:MM"
time = Time.now.strftime("%I:%M %p")
=> "04:05 PM"
1
2
3
# Returns the time formatted as "HH:MM:SS"
time = Time.now.strftime("%H:%M:%S %p")
=> "16:06:43 PM"
1
2
3
4
5
6
7
8
9
10
11
# Move forward from time in hours
Time.zone = 'Eastern Time (US & Canada)'
=> 'Eastern Time (US & Canada)' 
now = Time.zone.now
=> Sun, 02 Nov 2014 01:26:28.558049687 EDT -04:00
now.advance(hours: 1)
=> Sun, 02 Nov 2014 01:26:28.558049687 EST -05:00

# Move forward from time in months
now.advance(months: 1)
=> Tue, 02 Dec 2014 01:26:28.558049687 EST -05:00

Options parameter includes keys for years, months, weeks, days, hours, minutes, seconds handling DST boundaries accurately.