Menu
Topics Index
...
`

Date Example - Java Example Program


Date Example
import java.util.*;

class DateExampleTest
{
    public static void main(String arg[])
    {
        try
        {
            // Get current date and time
            Date date = new Date(); // LINE A
            System.out.println(date);
            // Convert Date to String.
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); // LINE B
            String stringDate = dateFormat.format(date); // LINE C
            System.out.println(stringDate);
            // Convert String to Date.
            SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            String dateInString = "15/08/1947 02:25:56";
            date = df.parse(dateInString); // LINE D
            System.out.println(date);
        } catch (Exception e)
        {
            e.printStackTrace();
        }    
    }
}
OUTPUT

Fri Apr 18 14:25:43 IST 2014
18/04/2014 02:25:43
Fri Aug 15 02:25:56 IST 1947

DESCRIPTION

In this program, at LINE A we are getting the current date and time. At LINE C we are converting date to string format and string to date format at LINE D by using SimpleDateFormat at LINE B and Date class. The output varies as the time various so it need not be same as the present output.

THINGS TO TRY
  • Replace the code at LINE A with below shown code and see the difference in output.
    SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM yyyy H:mm:s:S:a");
    In the above code E represents Day in Week i.e. (Fri, Mon) depending upon the Day in week.
    MMM represents month in string i.e. (Jan, Feb, Dec) depending upon the month specified in the given date.
    yyyy represents the year. H represents hour in a day i.e. from (0~23).
    s represents seconds.
    S represents milliseconds.
    a is to represent meridian i.e. AM/PM.
  • Replace code at LINE A with code below.
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
    The output should produce hours and minutes of the particular date.

© meritcampus 2019

All Rights Reserved.

Open In App