javadatecalendarformatting

How to format a date with capitalized day and month names?


I'm from a Hispanic country and using a locale like new Locale("es", "ES"). I'm trying to format a date in this way:

Martes 7, Noviembre, 2013

I need the day name and the month name to begin with a capital letter as shown.

This is my code:

private static String formatDate(Date date) {
  Calendar calenDate = Calendar.getInstance();
  calenDate.setTime(date);
  Calendar today = Calendar.getInstance();
  if (calenDate.get(Calendar.DAY_OF_MONTH) == today.get(Calendar.DAY_OF_MONTH)) {
    return "Today";
  }
  today.roll(Calendar.DAY_OF_MONTH, -1);
  if (calenDate.get(Calendar.DAY_OF_MONTH) == today.get(Calendar.DAY_OF_MONTH)) {
    return "Yesterday";
  }
  // Guess what buddy
  SimpleDateFormat sdf = new SimpleDateFormat("EEEEE d, MMMMM, yyyy");
  // This prints "monday 4, november, 2013" ALL in lowercase
  return sdf.format(date);
}

But I don't want to use some split method or do something like that. Isn't there some pattern that I can include in the regexp to make it be uppercase at the begin of each word?

UPDATE I get "martes 7, noviembre, 2013" in all lower case.


Solution

  • You can change the strings that SimpleDateFormat outputs by setting the DateFormatSymbols it uses. The official tutorial includes an example of this: http://docs.oracle.com/javase/tutorial/i18n/format/dateFormatSymbols.html

    Reproduction of the example from the tutorial, applied to the "short weekdays":

    String[] capitalDays = {
        "", "SUN", "MON",
        "TUE", "WED", "THU",
        "FRI", "SAT"
    };
    symbols = new DateFormatSymbols( new Locale("en", "US"));
    symbols.setShortWeekdays(capitalDays);
    
    formatter = new SimpleDateFormat("E", symbols);
    result = formatter.format(new Date());
    System.out.println("Today's day of the week: " + result);