Date and time in Java

In this post, you will learn how to handle date and time in Java.

3 important classes to work with Date and time in Java are

  1. Date – Legacy date class.
  2. Calendar – calculating the difference between dates, adding, deleting duration from dates.
  3. SimpleDateFormat – formatting dates.

Below example illustrates how we can use Date, Calendar and SimpleDateFormat classes in Java.

package datetime;
import java.text.*;
import java.util.*;

public class DateTime {

    public static void main(String[] args) throws Exception{

        //SimpleDateFormat can be used to specify the format of date
        //example - yyyy/MM/dd HH:mm:ss, MM/dd/yyyy
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

        Calendar cal = Calendar.getInstance();

        System.out.println("Todays date -> "
                + dateFormat.format(cal.getTime()));

        //get future date by adding 15 days to current date
        cal.add(Calendar.DATE, 15);
        System.out.println("15 Days from today -> "
                + dateFormat.format(cal.getTime()));

        //get past date by subtracting 25 days from it.
        cal.add(Calendar.DATE, -25);
        System.out.println("25 days in the past -> "
                + dateFormat.format(cal.getTime()));

        //For comparing dates, use Date class
        Date date1 = dateFormat.parse("11-12-2020");
        Date date2 = dateFormat.parse("11-12-2016");
        Date date3 = new Date();

        System.out.println("date 1 -> " + dateFormat.format(date1));
        System.out.println("date 2 -> " + dateFormat.format(date2));
        System.out.println("date 3 -> " + dateFormat.format(date3));

        if (date1.before(date2))
            System.out.println("Date1 falls before Date2");

        if (date1.after(date3))
            System.out.println("Date1 falls after Date3");

        if (date1.equals(date2))
            System.out.println("Date1 and Date2 fall on same day");
    }
}

Here is the output of above Java example

Todays date -> 16-04-2016
15 Days from today -> 01-05-2016
25 days in the past -> 06-04-2016
date 1 -> 11-12-2020
date 2 -> 11-12-2016
date 3 -> 16-04-2016
Date1 falls after Date3

You may also like...