CodeGym /Courses /New Java Syntax /Introducing the Date type

Introducing the Date type

New Java Syntax
Level 8 , Lesson 8
Available
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);
}

"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 (29)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
cnsacramento Level 10, El Dorado Hills, España
11 March 2022
Almost all methods are deprecated :'(
Jonaskinny Level 25, Redondo Beach, United States
7 February 2022
While ok for the scope of the lesson, this is a very bad habit to start. If you see it in the wild, change it !! long msDay = 24 * 60 * 60 * 1000; <-- don't do the Date(or Calendar) class' job or you will likely be scorned by those that come after you.
Daniel Bressner Level 13, United Kingdom, United Kingdom
15 January 2022
Adding to the other commenters here - I agree there is value in learning old code because you're likely to encounter it in the wild, but I do wish CodeGym had some sort of compare and contrast resource here so we can see both the deprecated methods and what they've been replaced with.
Yordan Popov Level 12, Asenovgrad, Bulgaria
29 July 2021
Is it just me, or there`s something wrong with this one: 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!"); } }
Naughtless Level 41, Olympus Mons, Mars
21 May 2021
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 Vypirailenko Level 41, USA
22 May 2021
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 41, Olympus Mons, Mars
23 May 2021
Right. I didn't think of that. Thank you.
Justin Smith Level 41, Greenfield, USA, United States
13 July 2021
Knowing legacy code is good, but they're teaching new programmers to only use the deprecated code, which is not good. I'm guessing the page was written before Calendar became the norm? That was years ago, though.
Sinisa Level 11, Banja Luka, Bosnia and Herzegovina
8 March 2021
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 23, Szekesfehervar, Hungary
1 May 2020
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
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
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......
14 November 2019
A link to the Time Documentation Time Tutorials and Documentation