CODE
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();
}
}
}
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.
LINE A
with below shown code and see the difference in output. SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM yyyy H:mm:s:S:a");
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.LINE A
with code below. SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");