Alright Stop, Strftime

Isaac Anzaroot
3 min readJun 3, 2021

--

During my most recent project, I dipped my toe into the proverbial pool of Ruby’s time and date classes. What I found was… discouraging and I ended up not using it, but I did learn a few things. What we’re discussing now, is the strftime method.

Date, Time, and DateTime

Before we talk about strftime, we need to know about the 3 classes of time and date.

Let’s start with the Date class.

We initialize it with Date.new and we can pass in 3 arguments. The first value we pass is the year, then month, and finally, day.

We can also parse strings. For example:

There are methods we can call but we’ll just show a few for now.

We can call Date.today for the current date and we can call methods on that date to return some values.

Wday returns a number corresponding to the day of the week starting with 0. So Sunday is 0, Monday is 1, etc.

Mday returns the day of the month. It’s the 3rd.

And yday returns the day of the year.

On to the Time class.

Time works very similarly to the Date class, but it returns it a little differently.

Time is stored internally as the number of seconds with subsecond since the Epoch, 1970–01–01 00:00:00 UTC. https://ruby-doc.org/core-3.0.0/Time.html

It can also accept arguments like the Date class with further options for the hour, minutes and seconds.

And finally DateTime.

Here we have combination of the Date class format and the Time class format.

You can call most of the same methods for all three of these classes.

Strftime

We made it. Strftime. What is it?

Well to put it simply, it converts a Date, Time, or DateTime class, into a string and formats them based on the arguments passed. Unclear? Let’s have a look.

We’ve called strftime on our DateTime class and it output a formatted string.

What are those percentage signs and letters in parameters? Well, those are instructions that strftime takes and uses to format the DateTime class.

There are quite a few of them and we’re not going to go through them all but there is wonderful website that will not only explain what each of them do, but also allow you create your own formatting string and display what it will look like.

--

--

No responses yet