tags:

views:

158

answers:

3

Given a month string such as:

    "Feb"
or
    "February"

Is there any core java or third party library functionality that would allow you to convert this string to the corresponding month number in a locale agnostic way?

+2  A: 

SimpleDateFormat.parse.

Paul Tomblin
+9  A: 

You could parse the month using SimpleDateFormat:

    Date date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse("Feb");
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int month = cal.get(Calendar.MONTH);
    System.out.println(month == Calendar.FEBRUARY);

Be careful comparing int month to an int (it does not equal 2!). Safest is to compare them using Calendar's static fields (like Calendar.FEBRUARY).

Bart Kiers
Having looked into joda time, it is more concise, robust, and gives the expected month number. Is there a reason why SimpleDateFormat should be preferred? If not I see no reason why not to pick Joda time as the answer... thanks
calid
The only advantage I can think of is that the SimpleDateFormat doesn't need any 3rd party jar. But if it's all the same to you, I'd go for the (superior) functionality of Joda.
Bart Kiers
+4  A: 

An alternative to SimpleDateFormat using Joda time:

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

    // if default locale is ok simply omit '.withLocale(...)'
    DateTimeFormatter format = DateTimeFormat.forPattern("MMM");
    DateTime instance        = format.withLocale(Locale.FRENCH).parseDateTime("août");  

    int month_number         = instance.getMonthOfYear();
    String month_text        = instance.monthOfYear().getAsText(Locale.ENGLISH);

    System.out.println( "Month Number: " + month_number );
    System.out.println( "Month Text:   " + month_text   );

    OUTPUT:
        Month Number: 8
        Month Text:   August
calid
You still need to take locale into account.
BalusC
fixed... always forget that... you mean the whole world doesn't speak english? :)
calid