Date Format
By Ramakrishna on Nov 8, 2008 in Java Interview Questions
Java Date Class
Date class is also useful to handle date and time (In this you can retrieve the date and time and change it in our wish)
1) To create an object to Date class
Date d=new Date()
Here d represents Date class object of date ,This object defiantly stores system date and time.
2) Format the date and time,using getDateInstance() or getTimeInstance() or getDateTimeInstance() methods of Date Format class
Syntax: DateFormat fmt=DateFormat.getDateInstance(formatConst,region);
Ex: DateFormat fmt=DateFormat.getDateInstance(format.MEDIUM,LOCALE.UK);
Note: Four types of formting constants are there they are
–> DateFormat.LONG
–> DateFormat.FULL
–> DateFormat.MEDIUM
–> DateFormat.SHORT
3) Applying format to Date object is done by format() method.
String str =fmt.format(d);
Example: Write a Sample Programe for Date Format class
//Formating and displaying system date and time
Class MyDate
{
public static void main(String[] args)
{
// Create Date obj
Date d=new Date();
//Store format information into DateFormat object
DateFormat fmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.SHORT,Locale.UK);
// apply format information from fmt to Date object
String str=fmt.formt(d);
//display formated date and time
System.out.println(“System Date and Time:”+str);
}
}
