DateFormat format(Date obj) method in Java
Last Updated :
23 Nov, 2022
The format() method of DateFormat class in Java is used to format a given Date object into a string representing Date/Time.
Syntax:
String format(Date date)
Parameters: This method accepts a single parameter date which is a Date object.
Return Value: This method returns a String which is the formatted date-time value of the Date object passed as a parameter to the method.
The below programs illustrate the above method:
Program 1:
Java
import java.text.DateFormat;
import java.util.Date;
public class GFG {
public static void main(String[] args)
{
Date currentDate = new Date();
String dateToStr = DateFormat.getInstance()
.format(currentDate);
System.out.println("Formatted Date String: "
+ dateToStr);
}
}
|
Output:
Formatted Date String: 2/27/19 3:31 PM
Time complexity: O(1)
Auxiliary space: O(1)
Program 2:
Java
import java.text.DateFormat;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Date date = new Date(2323223232L);
String dateToStr = DateFormat.getInstance()
.format(date);
System.out.println("Formatted Date String: "
+ dateToStr);
}
}
|
Output:
Formatted Date String: 1/27/70 9:20 PM
Time complexity: O(1)
Auxiliary space: O(1)
Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)\
Share your thoughts in the comments
Please Login to comment...