To get the current month name from the system we can use java.util.Calendar
class. The Calendar.get(Calendar.MONTH)
returns the month value as an integer starting from 0 as the first month and 11 as the last month. This mean January equals to 0, February equals to 1 and December equals to 11.
Let’s see the code below:
package org.kodejava.example.util;
import java.util.Calendar;
public class GetMonthNameExample {
public static void main(String[] args) {
String[] monthName = {"January", "February",
"March", "April", "May", "June", "July",
"August", "September", "October", "November",
"December"};
Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];
System.out.println("Month name: " + month);
}
}
On the first line inside the main method we declare an array of string that keep our month names. Next we get the integer value of the current month and at the last step we look for the month name inside our previously defined array.
The example result of this program is:
Month name: September
The better way to get the month names or week names is to use the java.text.DateFormatSymbols
class. The example on using this class can be found on the following links: How do I get a list of month names? and How do I get a list of weekday names?.
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Why don’t you use:
Hi Chariya,
Yes you can do it that way to make things simpler. In this example I was trying to introduce the
Calendar.MONTH
constant of the calendar class.