Topics Index

Date Example - Java Example Program

Date Example
import java.util.*;

class DateExampleTest
    public static void main(String arg[])
            // Get current date and time
            Date date = new Date(); // LINE A
            // Convert Date to String.
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); // LINE B
            String stringDate = dateFormat.format(date); // LINE C
            // 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
        } catch (Exception e)

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


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.

  • 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