Java Month Get getMonth(String name)

Here you can find the source of getMonth(String name)

Description

Returns the month number from a given month name.

License

Open Source License

Parameter

Parameter Description
name Name.

Exception

Parameter Description
IllegalArgumentException Name is null!

Return

Number.

Declaration

public static int getMonth(String name) 

Method Source Code

//package com.java2s;
/* Util.java//from  w  w  w.ja v a  2 s .c o  m
 * 
 * Networking ME
 * Copyright (c) 2013 eMob Tech (http://www.emobtech.com/)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

public class Main {
    /**
     * <p>
     * Returns the month number from a given month name.
     * </p>
     * @param name Name.
     * @return Number.
     * @throws IllegalArgumentException Name is null!
     */
    public static int getMonth(String name) {
        if (isEmptyString(name)) {
            throw new IllegalArgumentException("Name is null!");
        }
        //
        name = name.trim().toLowerCase();
        //
        final String[] months = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov",
                "dec" };
        //
        for (int i = 0; i < months.length; i++) {
            if (name.startsWith(months[i])) {
                return i;
            }
        }
        //
        return -1;
    }

    /**
     * <p>
     * Checks whether the given string is null or empty.
     * </p>
     * @param str The string.
     * @return true null/empty.
     */
    public static boolean isEmptyString(String str) {
        return str == null || str.trim().length() == 0;
    }
}

Related

  1. getMonth(String date)
  2. getMonth(String dateKey)
  3. getMonth(String datetime)
  4. getMonth(String day)
  5. getMonth(String f)
  6. getMonth(String pFormattedDate)
  7. getMonth(String quarters)
  8. getMonth(String sMonth)
  9. getMonth(String startTime)