1. Date
class and Unix time
From the very beginning of Java, the language has had a special class for working with times and dates — Date
. Over time, several more classes for working with dates appeared, but programmers continue to use the Date
class even today.
This is because it is very simple and convenient. And as a programmer, you will definitely encounter it in any real project. Whether to use it or not is your choice, but you must know it. So give it a few minutes of your precious time.
What makes the Date
class so good? Its simplicity.
The Date
class stores date and time information as the number of milliseconds that have elapsed since January 1, 1970. That's is a lot of milliseconds, so the long
type is used to store them.
Why since 1970 specifically? This is so-called Unix time: it is how the Unix operating system, which is the grandfather of all modern operating systems, keeps time.
But you can very easily find out how much time has passed between two dates: just subtract one date from the other, and you get the time difference between the dates to the nearest millisecond.
Here are some useful examples of working with the Date
class.
2. Getting the current date
To get the current time and date, simply create a Date
object. Each new object stores the time when it was created. It looks very simple:
Date current = new Date();
After executing this command, the current
variable will store a reference to the created Date
object, which will internally store the time of its creation — the number of milliseconds that have elapsed since January 1, 1970.
Displaying the current date on the screen
To display the current date, simply: a) create a new Date
object, b) print it to the screen using the System.out.println()
method.
Example:
Code | Console output |
---|---|
|
|
Here's what the console output means:
Text | Interpretation |
---|---|
Thursday | Thursday |
February 21 | February 21 |
14:01:34 | hours : minutes : seconds |
EET | Time zone: East European Time |
2019 | Year |
3. Setting a specific date
We figured out how to get the current time, but how do we create a Date
object that stores a different date or time?
Again, everything is simple here. To set a specific date, you need to write code like this:
Date birthday = new Date(year, month, day);
Everything is simple and obvious, but there are two nuances to be aware of:
- The year must be counted from 1900.
- Months are numbered from zero.
This is another legacy of the Unix operating system: on Unix, programmers denoted the year using two digits. Instead of 1977, they simply wrote 77. So 77 is the correct year if we count from 1900.
For example, I was born on March 21, 1989. March is the third month, so I need to write:
Code | Console output |
---|---|
|
|
Months are numbered from zero, but days are not That's a little strange, right?
We think true programmers should have prevailed and numbered the days of the month from zero too. Oh, these conformists 🙂
Setting a specific time
Setting a specific time is also quite simple: for this, you need to write a statement like this:
Date birthday = new Date(year, month, day, hour, minutes, seconds);
Hours, minutes and seconds are numbered from zero: let the programmer inside you breathe a sigh of relief.
Example:
Code | Console output |
---|---|
|
|
We set the time 12:15 and the date June 4, 2005. This is a little difficult for a non-programmer to read, but it works as it should.
4. Working with elements of a date
You can do more with a Date
object than just display it. It has methods that let you get individual elements of the internally stored date:
Method | Description |
---|---|
|
Returns the year of the date relative to 1900. |
|
Returns the month of the date (months are numbered from zero) |
|
Returns the day of the month |
|
Returns the day of the week |
|
Returns the hours |
|
Returns the minutes |
|
Returns the seconds |
Example:
Code | Console output | Note |
---|---|---|
|
|
2005 June day of the month Saturday |
By the way, a Date
object not only lets you get individual elements of a date, but also change them:
Method | Description |
---|---|
void setYear(int year)
|
Changes the year of the date. The year is indicated relative to 1900. |
void setMonth(int month)
|
Changes the month of the date (months are numbered from zero) |
void setDate(int date)
|
Changes the day of the month |
void setHours(int hours)
|
Changes hours |
void setMinutes(int minutes)
|
Changes minutes |
void setSeconds(int seconds)
|
Changes seconds |
5. Milliseconds
As we said previously, the Date
object stores the number of milliseconds that have elapsed since January 1, 1970.
If we need that number, we can get it from the Date
object:
long time = date.getTime();
The getTime()
method returns the number of milliseconds stored inside the Date
object.
Not only can you get the number of milliseconds, but you can also change that number in an existing object:
Date date = new Date();
date.setTime(1117876500000L);
By the way, you can write this even more concisely by passing the time to the Date
object right when it is created:
Date date = new Date(1117876500000L);
6. Comparing dates
If you want to compare two dates and find out which one came first, you have three options
The first way is to simply compare the number of milliseconds they each store:
if (date1.getTime() < date2.getTime())
The second way is to use the before()
method of a Date
object:
if (date1.before(date2))
It reads like this: if date1
comes before date2
, then...
The third way is to use the after()
method of a Date
object:
if (date2.after(date1))
It reads like this: if date2
is after date1
, then...
7. DateFormat
class
Remember, when we displayed the date on the screen, we saw something like this: Thu Feb 21 14:01:34 EET 2019
. Everything seems correct, but the format is more how a date would be displayed for programmers rather than normal humans. We want to display the date more clearly for users. Something like Tuesday, February 21
.
And without the year. Or with a year, if necessary. In general, we want to be able to display the date in different ways.
There is a special class for this: SimpleDateFormat
.
Example:
Code |
---|
|
Console output |
|
Look at what the program displayed: Jun-04-2005
. That's not at all what it used to be.
The difference is that we displayed not the Date
object itself, but a special string obtained by calling the format()
method on a SimpleDateFormat
object. But that's not even the main point here.
When the SimpleDateFormat
object was created, we passed in the string "MMM-dd-YYYY"
as a parameter. It is this string that conveys the date format that we ultimately saw in the console output.
- MMM indicates to display the name of the month, abbreviated using three letters
- dd indicates to display the day of the month
- YYYY indicates to display the year using four digits
If we want to output the month as numbers, then instead of MMM
, we need to write MM
, which yields the pattern "MM-dd-YYYY"
. The screen output will be 06-04-2005
We will discuss this class in more detail later.
8. Date.parse
method
The Date
class can do something else interesting and useful — it can get a date from a string. Or, as programmers say, it can parse a string.
It has the special parse()
method for this. Parsing looks like this:
Date date = new Date();
date.setTime( Date.parse("Jul 06 12:15:00 2019") );
By the way, this code can be written more compactly:
Date date = new Date("Jul 06 12:15:00 2019");
We'll consider the parsing of strings in more detail in other lessons.
GO TO FULL VERSION