For printing months in different formats, we are going to use two classes of java.util package. That is the first one Calendar class and another one is Formatter class. From Calendar class use getInstance() method to get instance (time and date information) of calendar according to the current time zone.
Example:
Input : 18-11-2020 Output: December Dec 12 Explanation: Here, month starts from 0. Input : 18-5-2019 Output: June Jun 06
Syntax:
public static Calendar getInstance()
Return Value: The method returns the calendar.
Formatter Class:
Formatter class in java is mainly used to displaying a number, string, time, date any format you like. Following are the conversion characters are used for formatting dates in our program.
- %tB- Full month name like “January” “March”.
- %tb-Abbreviated month name like “Jan”, “Feb”.
- %tm-Months formatted as two digits.
The format used in the below implementation:
"November" "NOV" "11"
Implementation:
Java
// Java Program to Print the Months in Different Formats import java.util.Calendar; import java.util.Formatter; public class MonthFormates { public static void main(String args[]) { // create objects of date formatter class. Formatter fmt1 = new Formatter(); // create object of calendar class. // cal object contains current date of system Calendar cal = Calendar.getInstance(); // setting a new date and Here 5 means // June because Months starts from 0 cal.set( 2019 , 5 , 18 ); // print month in different ways. fmt1.format( "%tB %tb %tm" , cal, cal, cal); System.out.println( "Output: " + fmt1); } } |
Output: June Jun 06