Sign In | Subscribe

Enter your Sign on user name and password.

Forgot password?
  • Follow us on:
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Introduction to Ruby
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

Dates and Times

  • In this lesson, we will go over how to represent a date and time in ruby, changing time zones, and the three classes Time, Date, and DateTime.
  • The Time class represents both dats and times. It contains a thin layer over the system date and time functionality provided by the operating system.
  • Popular Methods: now, at, year, day, month, hour, min, sec, usec, zone, to_a, local, utc, strftime
  • The Date library loads up two classes Date and DateTime
  • use new to create a new date object
  • the parse method allows you to represent date and time through a date object
  • the today method will create a new date object denoting the present date
  • Methods to define components of a date: year, month, day, sunday?, thursday?

Dates and Times

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Dates and Times 0:12
  • Time Class 0:38
  • Methods of the Time Class 1:43
    • now
    • at(time)
    • Epoch & Unix Timestamp Conversion Tools
  • Components of a Time 5:07
  • Convert Time to an Array 5:54
    • to_a
  • Creating a New Time 6:48
    • Time.local
    • Year is required
    • Time.utc
    • What should be specified
  • More Methods of the Time Class 10:16
    • strftime(string)
    • RDoc
  • Date Library 16:46
  • Initializing a New Date 17:08
  • Parsing Dates 18:28
    • parse(string)
  • Today's Date 19:19
  • Tomorrow's Date 20:22
    • Next
    • Next week
  • Count Down 21:26
  • Count Up 22:37
  • Components of a Date 23:20
  • Converting to Datetime 23:48
    • to_datetime
  • Initializing a Datetime 24:24
  • Converting to Time 25:23
    • self.to_time

Transcription: Dates and Times

Welcome back to

Today's lesson is on dates and times.0002

Today's lesson is over, "How do we represent a date and time in Ruby?"0010

We're going to go over the components of a date and time, and the three classes: Time, Date, and DateTime.0016

These are the main classes for the date and time functions.0032

The first thing we're going to look at is the Time class.0037

With the Time class, you can represent date and time.0041

This is a class that is a thin layer over the system date and time provided by the operating system.0045

Depending on your operating system, some platforms might have issues representing dates before 1970 or after 2038.0058

If you're on a 32-bit machine, it's more prone to having these issues.0067

The Time class--mostly you want to use this for current dates and times--for what time it is now and the day it is now.0079

This is the recommended usage for it.0094

What are the methods of the Time class? The most common one you will use is the now.0100

Now returns a time object initialized to the current system time.0106

To call this, all you do is use will retrieve the current time from your system.0117

The next method we will look at is at.0124

What at does is, you pass in a value of time, and this creates a new Time object with the given time you pass in.0128

Time is the number of seconds from epoch, so if I do with 0, the time it's going to give me is 1969, December 31st, 4 o'clock, and here is your time zone.0137

If I pass in this huge number, say 1.2 billion seconds, it's going to get me 2008.0157

I can also do, which will get me the current time, then to_i to convert it to number of seconds in integers, and then I can pass it, and it will get me the exact same object, essentially.0172

One question you might have is, "What is this number second from epoch?"0187

Let's take a look at that.0194

I'm loading up the epoch

You will see that, if I reload it...actually, in real time, notice that it tells me the epoch time, and it's this huge, huge number--in the billions.0204

But, you can also convert this epoch to human-readable; you take this number, you can click this timestamp, and it will say...for my time zone right now, it is Monday, October 15th, from that timestamp.0217

Now, what is this number, essentially?--let's go down here--what is epoch time?0232

This is the UNIX epoch, or UNIX time, or POSIX time, or UNIX timestamp.0239

It's better known as the UNIX timestamp.0244

This is the number of seconds that has elapsed since January 1st, 1970, at midnight.0246

It's a very common timestamp that is used.0252

It doesn't count leap seconds.0257

Literally speaking, the epoch is UNIX time zero.0259

Epoch is often used as a synonym for UNIX time, and many UNIX systems store this as an assigned 32-bit integer, which might cause problems generating 1920 to 38.0263

There you have it; go down here; you can see it in Ruby: it's just called

Convert to epoch:

Let's put here...this is actually UNIX time...I like to call it the UNIX timestamp.0287

Let's look at some of the components of this Time class.0306

I call; that is going to give me the current time.0310

If I pass .year to this object, it will tell me the year I'm at; day will give me the day in numeric terms; month will give me the month in numeric terms; hour; min is minutes; sec is seconds.0315

I can also get the microseconds using this usec method.0334

When we call zone, it will get me the time zone of this Time object.0339

It says my system is in Pacific Zone time; it gets me Pacific Daylight Time.0346

Also, this Time object--you can convert it to an Array.0354

All you do is pass to_a; this converts the components to an Array.0360

There is quite a specific Array it gives back.0367

This Array: the first element will be seconds, then minute, hour, day, month, year, wday, yday, isdst, and the zone.0374

If you do, t.to_a, this will get you back that Array--the time Array of elements here.0387

You could also use a method to create a new time.0406

For this one, we are looking at Time.local.0412

This creates a new time in your local zone.0415

How does it get that local zone? It gets it from your operating system.0419

To do this, it does take parameters; you can pass in a year, a month, day, hour, minute, and second.0425

The year is required; it needs at least one argument; the other arguments are optional, and it will just pass in a default of 0 for that.0432

This will create a new time; year is required; other arguments are optional.0443

If I call Time.local, I'm going to get my first value, 2010, as my year.0450

That is what I'm passing in; that is my required value.0456

Notice that I actually pass in the month, but as a three-letter month; I can pass in a numeric month or a letter; so I'm passing in Jun, and then a day and hour.0459

I call Time.local, pass these parameters in, and it's going to create me a Time object, and it's going to use those parameters I passed: 2010 and June 15th, 12 o'clock.0473

You can also create a new time in the UTC time zone, or GMT--those are both the same.0490

This, again, takes the exact same parameters: year, month, day, hour, minute, second.0496

It creates a new time interpreted as UTC.0504

You can also use GM for GMT; for that, just do, and go ahead and pass the time values in there.0507

For my example here, notice I used Time.utc; I passed in the year 2000; here is the month, which is January; day is the 1st; and hour is the first hour.0524

Here is our it creates a new Time object, January 1st, 2000, at 1 o'clock.0540

Remember, the hour is from 0 to 23, so 0 will get me midnight; 23 will get me 11 p.m.0548

There are some specificities to this local and UTC--to the parameters you pass in.0568

As I said, year must be specified; month may be specified by numbers from 1 to 12, or the three-letter English month name.0576

That is just the lowercase, like jan or jun...or December, dec...0589

The last one--I just told you about this--hours are specified on a 24-hour clock, which is 0 to 23.0604

There are quite a bit of methods in this Time class.0615

If I create a new object,, I can start calling these.0620

One of these--I would call utc?; this will tell me true or false--is this part of the UTC time zone?0625

This will pass either a true or false value.0635

Then, if I call zone, it returns me the time zone of this Time object.0638

I can also call getutc, and it will convert this time to a UTC time and tell me what time that is.0646

I can also call getlocal, and it will convert the time to the local zone time.0652

If I were to call, and getlocal, it would get me the same time, because it is the same zone it's working in anyway.0657

I can also check what day it is; I can say, "Is it a Sunday?" by just calling sunday?; "Is this time Monday?"--monday?, and Tuesday, tuesday?.0665

One really popular method for time manipulation is this strftime method.0682

You might have seen it in other languages, too.0690

I think that is one of the reasons you see it here--because it is so popularly used in C languages and other languages.0693

This formats the time according to the directives in the string, and these directives begin with a percentage character sign.0699

There are quite a bit of directives; let's go through an example.0708

If I go ahead and do, and I'm just going to pass in the strftime, and I'm saying, "OK, I have this Time object; I have a certain way I want to output it."0712

I want to do year, month, day, and then show the hour, minute, seconds to it.0723

So, for my directive, I have my %Y for year, my %m for month, %d for day, and then I have my hour, my minute, and seconds.0728

With that gets me my output for that Time object.0751

There are quite a bit of directives; let's look at them now.0759

Here we are at the RDoc for the Time class; we are looking at strftime.0766

Notice here, it says, "Formats time according to the directives in the given format string"--uses a percentage character...0775

After this percentage character, you do have quite a bit of modifiers here.0781

You have the flags, width, modifier, and conversion.0791

With the flags, it says you can pass the minus sign for "don't pad a numerical output."0798

Underscore: "use spaces for padding"; zero for "zeros for padding"; carat for "upcase the result string"; percentage: "change case"; colon for the %z.0806

What we want to look at is the format directives here.0820

We already looked at %Y; this is year with century; we can also do %c, which rounds it down, and %y, which will take them out of 100--so it just shows you the two numbers.0824

So, for 2012, it would just show 12.0841

Then, you have different directives with the lowercase m, which will be the month of the year, zero-padded with a zero.0844

You can also pass this underscore, which won't have it zero-padded, and -m will have no padding at all.0853

Then you can do capital B for the full month name; lowercase b will just be the three letters, and %h will also be an equivalent.0863

Then you have days of the month--you can do it non-padded, blank-padded (it would be d or e)--and then you can do the day of the year with the %j.0878

There are also some directives for the time.0890

Again, they have zero-padded and blank-padded: capital H would be zero-padded; lowercase k is blank.0894

Capital I will be zero-padded for the twelve-hour clock, and %l will be the twelve-hour clock that is blank-padded.0902

You can do the meridian indicators--pm/am, minutes of the hour, seconds of the minute (capital M, capital S)...0911

You can also get the milliseconds and the fractional seconds in digits.0919

There are also directives to get the weekday; you can get the full weekday name, the abbreviated name, and the numeric output--the day of the week.0928

There are also some things with the ISO 8601, so you can get some directives through that.0940

You can get the number of seconds from Epoch, which is the UNIX timestamp.0950

They also have combinations of it--a lot of common combinations; if I do %c, it will get my date and time; %D will get my date with month/day/year.0956

I can also run these combinations of 12-hour time, 24-hour time...and there are combinations that have already built that in there, since most commonly, you will use hour, minute, and second.0968

It's nice to have these combinations already built in there for you.0979

You will notice that they gave you a lot of common ones you might see, that you might want to use.0987

They have quite a bit of examples there, too.0994

That is the strftime method.0997

Next, we're going to look at the Date library.1005

To use it, you just require date, and this loads up two classes: one is Date, and one is DateTime.1008

These dates in Ruby are handled using the Date class.1019

First, let's look at initializing a new date.1026

To create a Date object, it is denoted with the given calendar date; so, by default, it does have some values if you don't pass anything; I can just do; it will get me a year that is -4712, a month of 1, and a day of 1.1030 probably want to add in your own values.1047

I have an example here: all you do is call, and I'm passing in 2011, month is 10, day is 10; it's going to create a new Date object.1052

This is going to be a Date object.1064

That Date object is going to have defined October 10, 2011.1069

I can also pass in a Date object with just a year, and that will give me a Date object of 2012, January 1st.1075

Notice that fourth argument with new: it says "calendar"; I can actually use a specific calendar type.1084

Two popular ones are...I can specify one with the Date::Gregorian, or I can pass it with Date::Julian, and it will make sure that date follows that calendar setup.1092

Also, with the Date object, we can parse dates, and it's pretty smart on how it does it; it allows me to try different combinations.1108

I call Date.parse, pass in the string...this will parse the given representation of date and time, and it returns a Date object.1119

So, I call Date.parse('2001-01-01'); it will create my new Date object using that.1131

I can do the same without dashes; it will recognize it and be able to parse it.1138

I can also do month, day, year, or day, month, year, and both of these will be equivalent; so these are still equal.1142

Let's look at today's date.1158

They do give you a method that is called today--just that will create a Date object denoting the present date.1161

Just call, and then I can call the to_s, the string method conversion, and I get the string method of the current date.1170

So, if I call t.to_s, it will say, "OK, today is October 15, 2012."1182

Plus, there are some methods in the date that are components of it that you can use--just like the Time one.1187

If I do--say--today's date is, I can actually interpolate out some of these methods; so I can call month, day, and year, and that will actually get me the output--10 over 15, 2012.1194

There is also a method called next: this 'n' is lowercase, so it's next; and that creates a new Date object denoting the following day.1218

What I do is, I take my current object, call .next to that, and it will give me a new object.1230

If I do, create a new object called tomorrow equals my object, and it will create a new object, which is the following day.1236

Also, with this and any other Date object, I can actually use the plus method and add on days, and it will create a new Date object to it.1251

It will automatically do all the typecasting and updating for me.1260

If I do tomorrow, let's say tomorrow is the 16th--and I add +7, it will create a new Date object for October 23rd, 2012.1265

Now, let's look at some of the countdown methods.1282

You don't see these in the Time method at all, but...1285

There is one method called downto, and I can count down, from the starting to the end; and it takes one parameter, which is the last day of the countdown.1289

Then, I can actually say, for each day it's counting down, to do some type of process.1303

This is a countdown of days, running block for each day--block being my code block.1309

For this, I do, get the current date, and then I say, "I want to go down two days," so I just pass t minus 2.1316

And then I tell it that I just want to output the day each time it does this.1327

For the first one, it's going to say today's date, October 15th.1331

Then, it's going to October 14th, October 13th, and this is the last day, so it's going to stop here, and that is the end of my countdown.1336

I can do this for each time; so I can do really complex stuff here; I don't have to just output the date.1343

I can output whatever I want in this code block.1349

There is also a method to count up: I can start at a certain date and count my way up.1354

Just like the downto, this one is called upto, but instead, it has a count up date, and again, I can pass in my code block for each date it's at.1360

For example, I just have, t; I say, "I want to go up to two days," so I take my current day and add 2 to that.1371

It's going to output October 15th for the first one; then it's going to go up to 16th; and then it's going to hit that countup date, that max: October 17th.1381

That is when it's going to stop counting up.1391

Let's look at some of the components of Date: there are not as many as Time.1397

It has year, month, and day: so year 2012, month 10, day 15.1402

It also has those common day methods: is it Sunday? Is it Thursday?1410

You just write sunday?, thursday?--it will tell you true or false--is it Sunday? is it Thursday?1415

Now, let's look at DateTime; this one allows us to pass in the time--the hour, minute, second--to it, also.1427

To do that, I take my Date object and call to_datetime.1436

This returns a DateTime object.1441

If I pass it from my current date today, since there isn't any time initially in it, it's going to create the new DateTime object, but the time elements will all just be 0 for now.1445

How do I initialize my own DateTime?--I want to specify the time to it.1462

You can just use the is actually date,

You can pass your month, day, hour, minute, second, and the offset.1481

This will create a DateTime object denoting the given calendar date.1486

For example, I have here year 2001, month February, day--the 3rd, hours--4, minutes--5, and seconds is 6.1492

It creates this new DateTime object; February 3rd, 2001, at 4:05 and 6 seconds.1505

It has a 0 offset, since I didn't set one.1517

You can also convert this to a Time: take your object, and call to_time to that, and this will return a Time object denoting the datetime.1524

To do this, I just do could use the today method, too--and just do d.to_time, and that will convert your object to Time.1540

Other than that, that is the end of dates and times in Ruby.1553

I hope this is useful, and see you next time on!1557