Java is a most powerful programming language, by which we can do many things and Java is an industry preferable language. So it has a huge field of features. Here we discuss one of the best features of Java, that is how we can represent Month in a short form or MMM Format.
There are two ways to do this using some classes:
Method 1: Using SimpleDateFormat and Date class
- Here Date class provides the current date and time, and SimpleDateFormat class use to format the date in some format, here the month will be shown in MMM format.
- SimpleDateFormat class comes under Text package in Java and Date class comes under the util package in Java. Date constructor initializes the object with the current date and time.
- SimpleDateFormat is a class for formatting and parsing date.
Example
Java
// Java Program to format the date in MMM // format using SimpleDateFormat() method 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); } } |
Nov
Method 2: Using Formatter class
- We can use Formatter class to print the month in short form.
- Here we use this class with Date class. There is format specifier “%tb” is use to print short month.
- There are many format specifier for other works also. If we use “%tB”, then it will become full month. See below code,
Java
// Java Program to Display Name of a Month in // (MMM) Format using Formatter class 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); } } |
Nov
Method 3: Use Formatter class with Calendar class
This class also returns the current date and time.
Example
Java
// Java Program to Display Name of a Month in // (MMM) Format using Formatter class with // Calendar class 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); } } |
Nov