Java Program to display date in given format. December, 27 2013
Objective
Write a Java program to display a date in a specific custom format (e.g., December, 27 2013).
Algorithm / Approach
- Create a
Dateobject. - Use
String.format()with specific Date formatting flags. %tBextracts the full Month name.%tdextracts the 2-digit day of the month.%tYextracts the 4-digit year.- Print the formatted string.
Test.java
import java.util.*;
class Test {
public static void main(String[] ar){
Date d = new Date();
String fd;
fd=String.format("%tB, %td %tY",d,d,d);
System.out.println(fd);
}
}
Expected Output
December, 27 2013
Explanation of the Program
- Java's
String.format()method (andSystem.out.printf()) includes powerful built-in date formatting capabilities, saving you from having to useSimpleDateFormatfor basic formatting. - Notice that we had to pass the
dobject three times into the format function, once for each `%t` flag.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)