Menu
Topics Index
...
`

Date Methods - Java Example Program


Date Methods
import java.text.SimpleDateFormat;
import java.util.Date;

class DateMethodTest
{
    public static void main(String arg[])
    {
        try
        {
            Date date1 = new Date(); // LINE A
            // Current date is stored in date1
            String dateInString = "15-08-1947 02:25:56";
            SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date date2 = df.parse(dateInString); // LINE B
            System.out.println("The date1 is after date2 : " + date1.after(date2));
            System.out.println("The date2 is before date1 : " + date2.before(date1));
            Date date3 = (Date) date1.clone();
            // Copies date1 into date3
            System.out.println(date1.compareTo(date3)); // LINE C
            // Prints 0
            System.out.println(date1.compareTo(date2)); // LINE D
            // Prints 1
            System.out.println("The date3 is equals to date1 : " + date3.equals(date1));
            System.out.println("Milli second for date1 : " + date1.getTime());
            System.out.println("Hash code for date1 : " + date1.hashCode());
            System.out.println("The date1 before setTime : " + date1);
            date1.setTime(10000); // LINE E
            System.out.println("The date1 after setTime : " + date1);
            String dateString = date1.toString(); // LINE F
            System.out.println("The string form of date1 : " + dateString);
        } catch (Exception e)
        {
            e.printStackTrace();
        }    
    }
}
OUTPUT

The date1 is after date2 : true
The date2 is before date1 : true
0
1
The date3 is equals to date1 : true
Milli second for date1 : 1397812350984
Hash code for date1 : 1947980109
The date1 before setTime : Fri Apr 18 14:42:30 IST 2014
The date1 after setTime : Thu Jan 01 05:30:10 IST 1970
The string form of date1 : Thu Jan 01 05:30:10 IST 1970

DESCRIPTION

In this program, At LINE A current date is stored in date1 and at LINE B the value of String dateInstring is stored in date2. The after, before, clone, compareTo, equals, getTime, hashCode, setTime() and toString methods are applied on these two dates, compareTo returns 0 if they are same else 1. The output varies as the time various so it need not be same as the present output for current date.

THINGS TO TRY
  • Try with the below code which prints current date and time.
    Date date = new Date();
    System.out.println(date);
  • Format a string to Date of format day/month/year(13/03/14).
    SimpleDateFormat sdf = new SimpleDateFormat("d/MM/yyyy");
    String dateNew = sdf.format(date);
    System.out.println(dateNew);
  • Compare two dates 1/1/1990 and 31/1/1990 using compareTo method which is shown at LINE C in the above example.

© meritcampus 2019

All Rights Reserved.

Open In App