The getInstance() method of DateFormat class will return the date and time formatter with the default formatting style for the default locale.
Syntax:
public static final DateFormat getInstance()
Parameter: This method doesn’t require any parameters.
Return value: This method will return the date format in a particular format.
Example 1:
Java
// Java program to illustrate // GetInstance() method // importing the required packages import java.text.DateFormat;
import java.util.Date;
class Testclass {
public static void main(String[] args)
{
// initializing the Date
Date d = new Date();
// initializing the DateFormat using getInstance()
DateFormat df = DateFormat.getInstance();
// printing the DateFormat return value as object
System.out.println( "DateFormat Object : " + df);
// formatting the current date into a string
String str = df.format(d);
// printing the current date
System.out.println( "Current date : " + str);
}
} |
Output
DateFormat Object : java.text.SimpleDateFormat@c88bcc54 Current date : 12/15/21, 8:23 AM
We can also display the date in the required format using SimpleDateFormat class.
Below is the example showing the use of SimpleDateFormat
Example 2:
Java
// Java program to illustrate // GetInstance() method // importing the required packages import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class Testclass {
public static void main(String[] args)
{
// initializing the Date
Date d = new Date();
// initializing the DateFormat using getInstance()
DateFormat df = DateFormat.getInstance();
// printing the DateFormat return value as object
System.out.println( "DateFormat Object : " + df);
// formatting the current date into a string
String str = df.format(d);
// printing the current date
System.out.println( "Current date : " + str);
// initializing the SimpleDateFormat
SimpleDateFormat sdf
= new SimpleDateFormat( "MM-dd-yyyy" );
// formatting the SimpleDateFormat into a string
String st = sdf.format(d);
// printing the formatted value
System.out.println( "Formatted Date : " + st);
}
} |
Output
DateFormat Object : java.text.SimpleDateFormat@c88bcc54 Current date : 12/15/21, 8:26 AM Formatted Date : 12-15-2021