
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
List Short Month Names in Java
In this article, we will learn to list up the short month names in Java. To do so we will be using DateFormatSymbols class from java.text package.
java.text: This package offers classes and interfaces for managing text, dates, numbers, and messages in a way that is not dependent on any specific language.
DateFormatSymbols is a class that helps you work with date and time information that can be adapted to different languages and regions. It includes things like the names of the months, the days of the week, and details about time zones.
Problem Statement
Write a Java program that lists the short names of all the months.
Output
Month [0] = Jan
Month [1] = Feb
Month [2] = Mar
Month [3] = Apr
Month [4] = May
Month [5] = Jun
Month [6] = Jul
Month [7] = Aug
Month [8] = Sep
Month [9] = Oct
Month [10] = Nov
Month [11] = Dec
Steps to list short month names
Following are the steps to list short month names ?
- First we will import the DateFormatSymbols class from java.text package.
- Initialize the Demo class.
- Use the getShortMonths() method to retrieve the short month names.
- Iterate through the array of short month names by using for loop.
- Print each month with its corresponding index.
Java program to list short month names
The following is an example ?
import java.text.DateFormatSymbols; public class Demo { public static void main(String[] args) { // short months String[] months = new DateFormatSymbols().getShortMonths(); for (int i = 0; i < months.length - 1; i++) { String month = months[i]; System.out.println("Month ["+i+"] = " + month); } } }
Output
Month [0] = Jan Month [1] = Feb Month [2] = Mar Month [3] = Apr Month [4] = May Month [5] = Jun Month [6] = Jul Month [7] = Aug Month [8] = Sep Month [9] = Oct Month [10] = Nov Month [11] = Dec
Code Explanation
In this program, we first import the DateFormatSymbols class from the java.text package. The DateFormatSymbols class is used to encapsulate localizable date-time formatting data, which includes month names. We then use the getShortMonths() method to get an array of short month names like "Jan", "Feb", etc.
After obtaining this array, we loop through it with a for loop, which iterates from 0 to months.length - 1, to avoid the last empty element in the array. Inside the loop, each month's name is printed along with its index using System.out.println().