The printf() method is used to print a formatted string, it accepts a string representing a format string and an array of objects representing the elements that are to be in the resultant string, if the number of arguments are more than the number of characters in the format string the excess objects are ignored.
Following table lists the various format characters to print date printf() method along with their description −
Format Characters | Description |
---|---|
'B' | The corresponding argument is formatted as full month name. |
'b' | The corresponding argument is formatted as abbreviated month name. |
'h' | The corresponding argument is formatted as abbreviated month name. |
'A' | The corresponding argument is formatted as the name of the day of the week (full). |
'a' | The corresponding argument is formatted as the name of the day of the week (short). |
'C' | The corresponding argument is formatted as year (Four-digit year divided by 100) |
'Y' | The corresponding argument is formatted as year (4-digit number). |
'y' | The corresponding argument is formatted as year (2-digit number). |
'j' | The corresponding argument is formatted as day of the year (3-digit number). |
'm' | The corresponding argument is formatted as month (2-digit number). |
'd' | The corresponding argument is formatted as day of the month (2-digit number with 0’s). |
'e' | The corresponding argument is formatted as day of the month (2-digit number). |
Example
Following example demonstrates how to format a date value using the printf() method.
import java.util.Date; public class Example { public static void main(String args[]) { //creating the date class Date obj = new Date(); System.out.printf("%tD%n", obj); System.out.printf("Date: %td%n", obj); System.out.printf("Month: %tm%n", obj); System.out.printf("Year: %ty%n", obj); } }
Output
11/10/20 Date: 10 Month: 11 Year: 20
Example
Following example demonstrates how to format an year using the java printf() method.
import java.util.Date; public class Example { public static void main(String args[]) { //creating the date class Date obj = new Date(); System.out.printf("%tD%n", obj); System.out.printf("Year: %tY%n", obj); System.out.printf("Day of the year: %tj%n", obj); } }
Output
11/10/20 Year: 2020 Day of the year: 315
Example
Following example demonstrates how to print the names of the month and day of a wee k using the printf() method of java −
import java.util.Date; public class Example { public static void main(String args[]) { //creating the date class Date obj = new Date(); System.out.printf("Date: %tD%n", obj); System.out.printf("Month (full): %tB%n", obj); System.out.printf("Month (abbrevation): %tb%n", obj); System.out.printf("Day (full): %tA%n", obj); System.out.printf("Day (abbrevation): %ta%n", obj); } }
Output
Date: 11/10/20 Month (full): November Month (abbrevation): Nov Day (full): Tuesday Day (abbrevation): Tue