Share This Article
If you want to format dates in Ruby, you can use the strftime
method.
The strftime
method is defined by the Time
class, and it accepts a string containing special format characters.
For example, if you want to get the current date as a string, you can use this code:
Time.now.strftime("%d %B %Y")
# "02 February 2020"
In the example above, we’re using some of the typical format characters like %d
for day, %B
for month, and %Y
for year.
There are many different format characters you can use with strftime
.
You can find the complete list of special characters in the strftime
documentation.
Parsing Dates & Times
For the cases when you have a date or time as a string, you can use the strptime
method to parse it and convert it to a Time
object.
Here’s an example:
Time.strptime("02 Feb 2020", "%d %b %Y")
# 2020-02-02 00:00:00 +0100
Notice that you need to provide the format of the string as the second argument to strptime
.
When you want to get the current timestamp as an integer, you can use the Time#to_i
method.
Time.now.to_i
# 1581167865
It’s also possible to create a Time
object from a timestamp using the Time#at
method:
Time.at(1581167865)
# 2020-02-02 16:44:25 +0100
Converting Time Zones
Let’s say you want to convert between time zones, you can use the in_time_zone
method.
Here’s an example:
time = Time.now
time.in_time_zone("Pacific Time (US & Canada)")
Note: This method is only available for Rails applications.
Formatting Dates & Times With Rails
In case you’re building a Rails application, you can use the to_formatted_s
method to format dates and times.
Here’s an example:
time = Time.now
time.to_formatted_s(format: :long)
# June 27, 2022 19:50
Note: This method is only available for Rails applications.
Summary
In this article, you have learned how to format dates using the strftime
method and how to parse a string into a Time object using the strptime
method. You also learned how to convert timestamps to Time objects and how to convert between time zones.
If you’re building a Rails application, you can use the to_formatted_s
method to format dates & times.