DateFormat format() Method in Java with Examples
DateFormat class present inside java.text package is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time. DateFormat class extends Format class that means it is a subclass of Format class. Since DateFormat class is an abstract class, therefore, it can be used for date/time formatting subclasses, which format and parses dates or times in a language-independent manner.
The format() method of DateFormat class in Java is used to format a given date into a Date/Time string. Basically, the method is used to convert this date and time into a particular format i.e., mm/dd/yyyy.
Syntax:
public final String format(Date date)
Parameters: The method takes one parameter date of the Date object type and refers to the date whose string output is to be produced.
Return Type: Returns Date or time in string format of mm/dd/yyyy.
Example 1:
Java
import java.text.*;
import java.util.Calendar;
public class GFG {
public static void main(String[] args)
{
DateFormat DFormat = DateFormat.getDateInstance();
Calendar cal = Calendar.getInstance();
System.out.println( "The original Date: "
+ cal.getTime());
String curr_date = DFormat.format(cal.getTime());
System.out.println( "Formatted Date: " + curr_date);
}
}
|
Output:
The original Date: Wed Mar 27 11:12:29 UTC 2019
Formatted Date: Mar 27, 2019
Example 2:
Java
import java.text.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
DateFormat DFormat = DateFormat.getDateTimeInstance(
DateFormat.LONG, DateFormat.LONG,
Locale.getDefault());
Calendar cal = Calendar.getInstance();
System.out.println( "The original Date: "
+ cal.getTime());
String curr_date = DFormat.format(cal.getTime());
System.out.println( "Formatted Date: " + curr_date);
}
}
|
Output
The original Date: Tue Jan 11 05:42:29 UTC 2022
Formatted Date: January 11, 2022 at 5:42:29 AM UTC
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...