Introducing the Date type

Introducing the Date type - 1

"Hi, Amigo. I want to tell you about an interesting type called Date. This type stores the date and time, and can also measure time intervals."

"Sounds interesting. Please go on."

"Every Date object stores a time in a rather interesting form: the number of milliseconds since January 1, 1970, GMT."

"Whoa!"

"Yeah. This number is so big there's not enough room for it in an int, so it has to be stored in a long. But it's really handy for calculating the difference between any two dates. You just do subtraction to find the difference with accuracy to the millisecond. It also solves the problem of the date line and daylight saving time."

"The most interesting part is that each object is initialized with the current time at its creation. To know the current time, you just need to create a Date object."

"How do you work with it?"

"Here are some examples:"

Get the current date:
public static void main(String[] args) throws Exception
{
     Date today = new Date();
     System.out.println("Current date: " + today);
}
Calculate the difference between the two dates
public static void main(String[] args) throws Exception
{
    Date currentTime = new Date();           // Get the current date and time
    Thread.sleep(3000);                      // Wait 3 seconds (3000 milliseconds)
    Date newTime = new Date();               // Get the new current time

    long msDelay = newTime.getTime() - currentTime.getTime(); // Calculate the difference
    System.out.println("Time difference is: " + msDelay + " in ms");
}
Check whether a certain amount of time has passed:
public static void main(String[] args) throws Exception
{
    Date startTime = new Date();

    long endTime = startTime.getTime() + 5000;  //    +5 seconds
    Date endDate = new Date(endTime);

    Thread.sleep(3000);              // Wait 3 seconds

    Date currentTime = new Date();
    if(currentTime.after(endDate))// Check whether currentTime is after endDate
    {
        System.out.println("End time!");
    }
}
Determine how much time has passed since the beginning of the day:
public static void main(String[] args) throws Exception
{
    Date currentTime = new Date();
    int hours = currentTime.getHours();
    int mins = currentTime.getMinutes();
    int secs = currentTime.getSeconds();

    System.out.println("Time since midnight " + hours + ":" + mins + ":" + secs);
}
Determine how many days have passed since the beginning of the year:
public static void main(String[] args) throws Exception
{
    Date yearStartTime = new Date();
    yearStartTime.setHours(0);
    yearStartTime.setMinutes(0);
    yearStartTime.setSeconds(0);

    yearStartTime.setDate(1);      // First day of the month
    yearStartTime.setMonth(0);     // January (the months are indexed from 0 to 11)

    Date currentTime = new Date();
    long msTimeDifference = currentTime.getTime() - yearStartTime.getTime();
    long msDay = 24 * 60 * 60 * 1000;  // The number of milliseconds in 24 hours

    int dayCount = (int) (msTimeDifference/msDay); // The number of full days
    System.out.println("Days since the start of the year: " + dayCount);
}
2
Task
Java Syntax,  level 8lesson 4
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

"The getTime() method returns the number of milliseconds stored in a Date object."

"The after() method checks whether the date we called the method on comes after the date passed to the method."

"The getHours(), getMinutes(), getSeconds() methods return the number of hours, minutes, and seconds, respectively, for the object on which they were called."

"Moreover, in the last example you can see that you can change the date/time stored in a Date object. We get the current time and date and then reset the hours, minutes, and seconds to 0. We also set January as the month and 1 as the day of the month. Thus, the yearStartTime object stores the date January 1 of the current year and the time 00:00:00."

"After that, we again get the current date (currentTime), calculate the difference between the two dates in milliseconds, and store it in msTimeDifference."

"Then we divide msTimeDifference by the number of milliseconds in 24 hours to get the number of full days from the beginning of the current year until today."

"Wow! This is so cool!"

Comments (24)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Naughtless
Level 13 , Olympus Mons, Mars
21 May, 08:36
So uhh, I'm getting warnings from IntelliJ that java.util.date is deprecated and we should migrate over to Calendar or java.time ? This sort of raises concerns that studying Date would be pretty useless. Although what is taught in this page seems pretty easy.
Alex
Level 41 , Solar System
22 May, 09:15
It is not useless, since as a Java Developer you will encounter a lot of legacy (old) code, which might include the Date class, so it's best to know about it and how it works.
Naughtless
Level 13 , Olympus Mons, Mars
23 May, 11:51
Right. I didn't think of that. Thank you.
Sinisa
Level 11 , Banja Luka, Bosnia and Herzegovina
8 March, 11:04
Shouldn't we practice List/Set/Map data structures first before we move on to the next topic? Why putting Date here?
Gellert Varga
Level 18 , Szekesfehervar, Hungary
1 May 2020, 21:23
Java from 1 January 1970 counts the milliseconds. This is right, You can try out.:) But if I write this code:
date.getYear();
then it does not return 50 (2020-1970=50), but 120. In other words:
date.setYear(0);  // = 1900.
date.setYear(88);  // = 1988.
date.setYear(-124);  // = 1776.:) etc.
Sanjay Chauhan
Level 28 , Delhi, India
10 February 2020, 07:08
Why don't lecture don't tell us that Date is deprecated and we shouldn't use it. #edit: They explained it later in the course. https://codegym.cc/groups/posts/java-time-calendar
yehuda b
Level 23 , Beersheba, Israel
6 February 2020, 19:01
When I did task 827 on level 8, which requires you to create a method to calculate, if the number of days passed since the first day of the year, is odd, i.e. JAN 3 should return true, JAN 4 false etc. , I tried using the logic from this lesson (in particular to set one date to JAN 1 00:00:00, and then calculating a later date in ms - JAN 1 in ms / ms per day) and it didn't work, I believe that getTime's accuracy is not down to the ms when you set a Date or Calendar instance, therefor when you set two date's to equal 00:00:00 in respect to time of the day, you won't get the amount of days passed, back accurately. Therefor using Calendar's.DAY_OF_YEAR method is better I wonder if my analogy is true......
Thomas
Level 9 , United States
14 November 2019, 17:26
A link to the Time Documentation Time Tutorials and Documentation
Ritik Singh
Level 8 , Gwalior, India
5 September 2019, 17:28
Happy teacher's Day Codegym and all its tutor
Vahan
Level 41 , Tbilisi, Georgia
14 July 2019, 16:33
A good delay in the array
Ewerton
Level 30 , Belo Horizonte, Brasil
27 June 2019, 20:59
Just a suggestion, I know we can just copy and paste these codes, but you should show the output below the example.
SefoBe
Level 16 , Paris, France
9 August 2019, 08:00
That would be great !
allthemore
Level 41
4 May 2019, 07:07
Methods
getHours(), getMinutes(), getSeconds()
are marked as deprecated. Any alternatives?
Jiří Martínek
Level 17 , Prague, Czech Republic
13 May 2019, 13:51
Whole Date class is deprecated. Since Java 8, the recommended way to work with time are classes LocalDate, LocalTime and LocalDateTime
allthemore
Level 41
13 May 2019, 15:14
Thank you! Will learn these classes too!