Search code examples
javaandroidsimpledateformatandroid-calendarandroid-date

How do I abbreviate month to 3 characters?


I am trying to abbreviate month in date time to 3 characters, say if the month is May, it shows May, but if the month is june, it should show Jun, and september should show sep and so on.

I have tried "MMM" but that does not work, it seems to return the full text for month.

Calendar mDate = Calendar.getInstance();
SimpleDateFormat mDateFormat = new SimpleDateFormat("EEEE, MMM d, yyyy", Locale.US);
mMyStartDate.setText(mDateFormat.format(mDate.getTime()));

Any ideas how to go about it? Also, I don't want anything else to change. just month, but have had no luck so far. Thanks in advance!


Solution

  • You can use the java.time package for this. There is a class DateTimeFormatter which you can utilize to format temporal objects, like LocalDateTime, LocalDate and LocalTime.

    This is a very simple example for formatting a date:

    public static void main(String args[]) {
        LocalDate today = LocalDate.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy");
        System.out.println(today.format(dtf));
    }
    

    The output (in my locale) is Mai 07 2019.

    Have a look at the built-in formats here.