views:

281

answers:

3

Hello

Does anyone know if there's a method in Joda Time or Java itself which takes either an int or a String as an argument, e.g. 4 or "4" and gives the name of the month back in short format, i.e. JAN for January?

I suppose long month names can be truncated and converted to upper case.

Thanks

Mr Morgan.

+3  A: 

I believe "MMM" will give the month name in Joda... but you'd need to build up an appropriate formatter first. Here's some sample code which prints "Apr" on my box. (You can specify the relevant locale of course.)

import org.joda.time.*;
import org.joda.time.format.*;

public class Test
{
    public static void main(String[] args)
    {
        // Year and day will be ignored
        LocalDate date = new LocalDate(2010, 4, 1);
        DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM");
        String month = formatter.print(date);
        System.out.println(month);
    }
}
Jon Skeet
Many thanks. I'll need this later.
Mr Morgan
Does google use Joda-time internally ?
mP
@mP: Yes, we do.
Jon Skeet
A: 

My last answer about using java.util.Calendar for this was a little more complicated than it needed to be. Here's a simpler version, although it still requires Java 6 or newer.

import java.util.Calendar;
import java.util.Locale;

public class Test
{
    public static void main(String[] args)
    {
        // Sample usage.
        // Should be "Apr" in English languages
        String month = getMonthNameShort(4);
        System.out.println(month);
    }
    /**
     * @param month Month number
     * @return The short month name
     */
    public static String getMonthNameShort(int month)
    {
        Calendar cal = Calendar.getInstance();
        // Calendar numbers months from 0
        cal.set(Calendar.MONTH, month - 1);
        return cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());
    }
}
R. Bemrose
A: 

In response to Jon's answer, you can further simplify that by using Joda's direct access for datetime classes.

String month = date.toString("MMM");
puug