Introduction to Date, Time and Calendar in Java

Introduction to Date, Time and Calendar in Java

By far managing time is the largest art humanity has wanted to achieve. Let’s at least learn to manage them in the virtual world. If you know the basics of Java, it’s high Time you learn it!
Date and Time Management in Java

Introduction to Date

Ok, so let’s start with the Date class, The Date class encapsulates the current system time and date.
To, get an instance of Date we have to use wither of its constructors mentioned below:

Date();
Date(long milliseconds)

The first one initializes the Date object with current date and time, whereas the second one initializes the date object with the number of millisecond specified which has elapsed after 1st January, 1970.

Let’s understand more by using below code:
import java.util.Date;
class DateExample{
 public static void main(String h[]){
  Date dt=new Date();//get instance
  System.out.println(dt);
  long msec=dt.getTime();
  System.out.println(msec);
 }
}
Output on the date of writing will be:
Thu Oct 23 16:31:25 IST 2014
1414062085858

First of all, as you can see I have imported java.util.Date class, that means that Date class resides in java.util package, the other classes we are going to work with will also be a part of this package. I have used a method in the code called getTime() which returns a long type value holding the number of millisecond expired after January 1, 1970.

Let’s try some other functions of Date class, with this code:
import java.util.Date;
class DateExample{
 public static void main(String h[]){
  Date dt=new Date();
  long m=299999999;
  Date dt1=new Date(m);
  Date dt2=new Date(40);
  System.out.println("current time:"+dt.getTime());
  if(dt.before(dt1))
   System.out.println("BEFORE");
  else
   System.out.println("AFTER");
  if(dt.after(dt2))
   System.out.println("AFTER");
  else
   System.out.println("BEFORE"); 
  
 }
}
Output:
current time:1414064118988
AFTER
AFTER

So what does this methods after(Date date) and before(Date date) with return type Boolean does?As the name suggests after returns true if the invoking date objects holds a greater value than the value supplied. The other unction before(Date date) does just the opposite. For dummies to understand clearly, it returns true if the invoking date object holds a date value earlier than the supplied one.

Some other Date functions are given below:


int compareTo(Date date)
Returns 0 if the value of supplied object and the invoking object is equal, negative if the value of invoking object is lesser than the supplied object, returns positive if the invoking object is earlier than the supplied one.

int hashCode()
Will return a hash code for the invoking Date object.

void setTime(long time)
Sets time according to milliseconds elapsed after January 1,1970.

String toString()
Returns a String for the invoking object.


Introduction to Calendar

As you see it’s a lot problematic to get desired components of time from Date, like if you just wanna work with the hour, or just with the month etc. Date will upset you. But don’t worry its Calendar on rescue.

Calendar is an abstract class which provides lots of method and constants to easily work with components of date and time.

So, how can we get components, look at the code below:
import java.util.Calendar;
class Experiments{
  public static void main(String args[]){
      Calendar cal=Calendar.getInstance();//to get an instance of Calendar
      String months[]={ "January","February","March","April",
           "May", "June", "July","August",
           "September", "October","November", "December" };
      //months array declared to get the required string for month
      //For date
      System.out.println("Date:");
      System.out.println( cal.get(Calendar.DATE) + "/"
           + months[cal.get(Calendar.MONTH)] + "/"
           + cal.get(Calendar.YEAR)
           );
      //for time
      System.out.println("TIME:");
      System.out.println(cal.get( Calendar.HOUR) + ":"
             + cal.get(Calendar.MINUTE) + ":"
             + cal.get(Calendar.SECOND)+":"
             + cal.get(Calendar.MILLISECOND)
             );
  }
}

Output:
Calendar Output

So how does it works, the get(int value), function fetches the correct component of time, as according to the constant integer value supplied. Calendar defines a lot of constant values, in the code I have used the important ones, DATE, MONTH, YEAR, HOUR, MINUT, SECOND, MILLISECOND. I think they are self explanatory. One more thing, why did I initialized an array and used it to get the month, because when returning month, Calendar returns an integer value ranging from 0 to 11. 0 for January and 11 for December. So, anyone can customize the values in the array and get represent a month in a different way [like ‘Jan’ instead of ‘January’].

Conclusion

Well, now you know about handling dates and time in Java. Practice it, play with the functions, also for more reference read the official documentation. If you like this content please share on Facebook, and follow us on Twitter. Also don’t forget to subscribe for regular updates. Keep Coding!

7 Comments Leave new

please suggest me the best book to learn servlets and jsp.
hoping for quick reply its urgent.....................

Reply

Head First Servlets and JSP

Reply

Hello Sir! Am a blogger and I want to become a professional blogger like you Pls can we chat on whatsapp? +2348185282153 am waiting for u sir!!!

Reply

Hello Sir! Am a blogger and I want to become a professional blogger like you Pls can we chat on whatsapp? +2348185282153 am waiting for u sir!!!

Reply

Hello Sir! Am a blogger and I want to become a professional blogger like you Pls can we chat on whatsapp? +2348185282153 am waiting for u sir!!!

Reply

please give the answer for this.
Write a program that should prompt user to input two line in hours and minutes format. After accepting the input it should initialize an object and add the two times accepted and output the same.

Reply

hello sir im a final year student and i want make a chatting application using java can u please help ,i need ur guidance sir please contact me [email protected] thanks sir.........

Reply

Make sure you tick the "Notify Me" box below the comment form to be notified of follow up comments and replies.