Date and Calendar functions in Java

Date and Calendar functions in Java

java.util.Date and java.util.Calendar are two important classes in Java used for date and time related operations. In this post we will see various Date and Calendar functions in Java.

To get System current date and time

To get System’s current date and time we just need to create an instance of Date class.

You can also use Calendar object to get current date and time. Here is an example.

To format date object

The date object created using an instance of Date class is not in a format we want. Most often we want to display the date in some format such as “dd/mm/yyyy” or “mm/dd/yyyy” etc. In such case we need to use date format classes. Here is an example using SimpleDateFormat class.

Here is a sample output of running the above program.

To Convert String to Date

Some times we may be having date and/or time in String format and we want to convert it into Date object so that we can do date related operations such as comparison etc. Here is an example which shows how to convert a String to Date object.

Date Comparison

We can use the methods defined in Date class such as equals(), before(), after() to compare whether two dates are equal, whether one date is after another date, whether one date is before another date respectively. We can also use compareTo() to compare dates for ordering.

Here is an example showing usage of above methods.

To calculate execution time of a code

Some times we want to calculate time taken to execute a particular piece of code. Here is an example to calculate time taken.

Below is a sample output of running the above code.

GregorianCalendar example

Here is a simple example using GregorianCalendar.

Below is the output of running the above program.

To set a date manually in Calendar object

Below is the output of running the above program.

Addition and subtraction of date using Calendar object

Below is a sample output of running the above program.

That’s all about Date and Calendar functions in Java. Hope you find this post useful. If you have any comments post it in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.