In this tutorial we are going to learn the current month name in java. We are also representing month in short format or else in MMM Format.
Introduction
In this we are using the java.time package. Mainly we are using two types of classes Date class and Formatter class.
Using SimpleDateFormat and date class
- Date class in java provides the date and time. While SimpleDateFormat class used to format date and time.
- Month will be shown in the form of MMM format.
- In java Date class is will comes under util package of java.
Example:
import java.util.Date; import java.text.SimpleDateFormat; public class GFG { public static void main(String args[]) { // initialize Date class Date date = new Date(); // initialize SimpleDateFormat class // it accepts the format of date // here it accepts the "MMM" format for month SimpleDateFormat month = new SimpleDateFormat("MMM"); //"format" use to format the date in to string String currentMonth = month.format(date); System.out.println(currentMonth); } }
Output:
May
Formatter class
- Formatter class in java is used to print the month in short form like MMM format.
- We are using the “%tb” specifier to print the month in short form.
- We also use the “%tB” specifier to print it in full name.
import java.util.Date; import java.util.Formatter; public class GFG { public static void main(String args[]) { // initialize Date class Date date = new Date(); // initialize Formatter class Formatter fm = new Formatter(); //"format" use to format the month name in to string // from the date object //"%tb" is use to print the Month in MMM form fm.format("%tB", date); System.out.println(fm); } }
Output:
May
Formatter class with Calendar class
We are using Calander class and Formatter class to get the current month name.
import java.util.Calendar; import java.util.Formatter; public class GFG { public static void main(String args[]) { // initialize Formatter class Formatter fm = new Formatter(); // initialize Calendar class //"getInstance()" return a Calendar instance based //on the current time and date Calendar cal = Calendar.getInstance(); // formatting month into string form the date object fm.format("%tb", cal); System.out.println(fm); } }
Output:
May