Core Java

Convert Month Name to Number in Java

When dealing with months in Java, we often use numbers because they provide a consistent format that works well across different languages and regions, as month names vary widely. This article will examine various methods to convert a month’s name to its corresponding number, starting with JDK solutions from pre-Java 8 and Java 8+, followed by approaches using the Joda-Time library.

1. Month Number Representations

When converting month names to numbers in Java, you can represent the month in various formats:

  • April -> 4: This is the full name of the month, typically used for display purposes in user interfaces.
  • APRIL -> 4: This version represents the full name of the month as stored in the java.time.Month enum, ensuring consistency in code.
  • Apr -> 4: This is the abbreviated form of the month name, consisting of three letters.

These different representations allow us to choose the appropriate format based on our application’s needs, whether for user interaction or internal processing.

2. Convert Month Name to Number Using JDK (Pre-Java 8)

Before Java 8, working with dates and times required either Calendar or Date classes. To convert a month name to its respective number, we can use SimpleDateFormat for parsing month names.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;


public class MonthNumberExample {

    public static int getMonthNumber(String monthName) {
        try {
            // Create a SimpleDateFormat instance with the month name pattern
            SimpleDateFormat sdf = new SimpleDateFormat("MMMM", Locale.ENGLISH);
            Calendar cal = Calendar.getInstance();
            // Parse the month name to a Date object
            cal.setTime(sdf.parse(monthName));
            // Return the month number (1-based, so add 1)
            return cal.get(Calendar.MONTH) + 1;
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid month name: " + monthName, e);
        }
    }

    public static void main(String[] args) {
        System.out.println("April -> " + getMonthNumber("April"));  
        System.out.println("June -> " + getMonthNumber("June"));    
    }
}

The SimpleDateFormat class utilizes the “MMMM” pattern to parse full month names, such as “January” and “February.” To retrieve the month value, we use the Calendar class, which represents months in a zero-based format (where January is 0). To convert this value into a more understandable, human-readable format, we simply add 1, so January becomes 1, February becomes 2, and so on.

Expected output from the given example:

April -> 4
June -> 6

3. Using Java 8+ java.time API

Java 8 brought in the java.time package, which improved how Java manages dates and times. Using Month from java.time, we can easily convert a month’s name to its corresponding number.

import java.time.Month;
import java.util.Locale;

public class MonthNumberJava8 {

    public static int getMonthNumber(String monthName) {
        try {
            // Get the month number using the Month enum
            Month month = Month.valueOf(monthName.toUpperCase(Locale.ENGLISH));
            return month.getValue();  // Month value is 1-based
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Invalid month name: " + monthName, e);
        }
    }

    public static void main(String[] args) {
        System.out.println("January -> " + getMonthNumber("January"));  
        System.out.println("August -> " + getMonthNumber("August"));    
    }
}

The Month enum offers a straightforward method to associate month names with their corresponding numbers, where valueOf converts a month name into a Month instance and getValue retrieves the associated number (1 for January, 2 for February, etc.), simplifying the code by removing the need for parsing.

The expected output of running the above code is:

January -> 1
August -> 8

In addition to using full month names, we can utilize ChronoField to directly convert abbreviated month names (like “Jan” for January or “Feb” for February) to their corresponding numbers.

import java.util.Locale;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;

public class MonthNumberJava8 {

    public static int getMonthNumberUsingChronoField(String monthName) {
        try {
            // Use DateTimeFormatter to parse the abbreviated month name with the "MMM" pattern
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM", Locale.ENGLISH);
            // Get the month number directly using ChronoField
            return formatter.parse(monthName).get(ChronoField.MONTH_OF_YEAR);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid month name: " + monthName, e);
        }
    }

    public static void main(String[] args) {
        System.out.println("Jan -> " + getMonthNumberUsingChronoField("Jan"));  
        System.out.println("Aug -> " + getMonthNumberUsingChronoField("Aug"));  
    }
}

The getMonthNumberUsingChronoField method utilizes a DateTimeFormatter with the “MMM” pattern to parse abbreviated month names and directly retrieves the month number using ChronoField.MONTH_OF_YEAR, making it an efficient solution for handling user inputs or data with abbreviated month names.

Expected output from the given example:

Jan -> 1
Aug -> 8

4. Convert Month Name to Number Using Joda-Time Library

Before Java 8, the Joda-Time library was the preferred choice for handling dates and times. Although Joda-Time has been largely replaced by the new java.time API, it’s still useful in older projects or when dealing with legacy codebases. Before we can use Joda-Time in a Java project, we need to include the library as a dependency.

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.7</version> <!-- Check for the latest version -->
</dependency>

Once the library is added, we can start implementing Joda-Time in our project.

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


public class MonthNumberJodaTime {

    public static int getMonthNumber(String monthName) {
        try {
            // Create a DateTimeFormatter with the month name pattern
            DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM");
            // Parse the month name to a DateTime object
            DateTime dt = fmt.parseDateTime(monthName);
            // Return the month number (1-based)
            return dt.getMonthOfYear();
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Invalid month name: " + monthName, e);
        }
    }

    public static void main(String[] args) {
        System.out.println("July -> " + getMonthNumber("July"));  
        System.out.println("September -> " + getMonthNumber("September"));    
    }
}

The DateTimeFormatter from Joda-Time is used to parse the month name, and DateTime extracts the month using getMonthOfYear, which returns a 1-based month number. For the example provided, the expected output is:

July -> 7
September -> 9

5. Conclusion

In this article, we explored different ways of converting a month’s name to its respective number in Java. We used:

  • SimpleDateFormat and Calendar in the pre-Java 8 approach.
  • The new Month enum from the java.time package in Java 8+.
  • The legacy Joda-Time library for older projects.

The Java 8 java.time package provides a more modern, cleaner, and more reliable way to handle dates, and it’s generally recommended for new code.

6. Download the Source Code

This article explored how to convert a month name to its corresponding number in Java.

Download
You can download the full source code of this example here: Convert month name to number in Java.

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button