Get month number from month name

后端 未结 4 1237
Happy的楠姐
Happy的楠姐 2020-12-17 14:34

I have this.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String monthName = br.readLine();

How to get mon

相关标签:
4条回答
  • 2020-12-17 14:38

    Solution in Java 8 for English month names.

    private int getMonthNumber(String monthName) {
        return Month.valueOf(monthName.toUpperCase()).getValue();
    }
    
    0 讨论(0)
  • 2020-12-17 14:42

    Another approach using java.text.DateFormatSymbols is this:

    public static int monthAsNumber(
      String  month,
      Locale  locale,
      boolean abbreviated,
      boolean caseInsensitive
    ) {
      DateFormatSymbols dfs = new DateFormatSymbols(locale);
      String[] months = (abbreviated ? dfs.getShortMonths() : dfs.getMonths());
    
      if (caseInsensitive) {
        for (int i = 0; i < 12; i++) {
          if (months[i].equalsIgnoreCase(month)) {
            return i; // month index is zero-based as usual in old JDK pre 8!
          }
        }
      } else {
        for (int i = 0; i < 12; i++) {
          if (months[i].equals(month)) {
            return i; // month index is zero-based as usual in old JDK pre 8!
          }
        }
      }
      return -1; // no match
    }
    

    The proposed signature of seach method illustrates the many possible variations. Example:

    System.out.println(monthAsNumber("MÄRZ", Locale.GERMANY, false, true));
    // output: 2 (zero-based!)
    

    If you want a month number starting with 1 then just add 1 to the result (more intuitive and also my recommendation).

    Starting with Java 8 you have a new variation, too, namely stand-alone months. While in English these month names are identical in other languages they are not always identical (for example in Czech language "leden" (January) instead of "ledna"). To achieve these stand-alone forms you can use Month.getDisplayName(...) (not tested):

    public static int monthAsNumber(
      String  month,
      Locale  locale,
      boolean abbreviated,
      boolean caseInsensitive,
      boolean standAlone
    ) {
      TextStyle style;
      Month[] months = Month.values[];
    
      if (abbreviated) {
        style = standAlone ? TextStyle.SHORT_STANDALONE : TextStyle.SHORT;
      } else {
        style = standAlone ? TextStyle.FULL_STANDALONE : TextStyle.FULL;
      }
    
      if (caseInsensitive) {
        for (int i = 0; i < 12; i++) {
          if (months[i].getDisplayName(style, locale).equalsIgnoreCase(month)) {
            return i; // month index is zero-based as usual in old JDK pre 8!
          }
        }
      } else {
        for (int i = 0; i < 12; i++) {
          if (months[i].getDisplayName(style, locale).equals(month)) {
            return i; // month index is zero-based as usual in old JDK pre 8!
          }
        }
      }
      return -1; // no match
    }
    
    0 讨论(0)
  • 2020-12-17 14:45

    If you have month name and you want integer number corresponding to that month try this

    try{   
            Date date = new SimpleDateFormat("MMM").parse(monthName);//put your month name here
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            monthNumber=cal.get(Calendar.MONTH);
            System.out.println(monthNumber);
    
     }
    catch(Exception e)
    {
     e.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-12-17 14:52

    Use Java's Calendar class. It can parse any given string into a valid calendar instance. Here is an example (assuming that the month is in english).

    Date date = new SimpleDateFormat("MMMM").parse(monthName);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    println(cal.get(Calendar.MONTH));
    

    You can specify the language in SimpleDateFormat:

    String monthName = "März"; // German for march
    Date date = new SimpleDateFormat("MMMM", Locale.GERMAN).parse(monthName);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    println(cal.get(Calendar.MONTH));
    

    By default, Java uses the user's local to parse the string.

    Keep in mind that a computer starts counting at 0. So, January will be 0. If you want a human readable date, you should format the calendar instance:

    SimpleDateFormat inputFormat = new SimpleDateFormat("MMMM");
    Calendar cal = Calendar.getInstance();
    cal.setTime(inputFormat.parse(monthName));
    SimpleDateFormat outputFormat = new SimpleDateFormat("MM"); // 01-12
    println(outputFormat.format(cal.getTime()));
    
    0 讨论(0)
提交回复
热议问题