Custom Date Format with Locale

Description

We can use DateTimeFormatter class ofPattern() method to create a DateTimeFormatter object with the specified format pattern and locale.


static DateTimeFormatter ofPattern(String pattern)
static DateTimeFormatter ofPattern(String pattern, Locale   locale)

Example

The following code shows how to create two formatters to format a date in "Month day, Year" format in the default locale and in the German locale.


DateTimeFormatter fmt1  = DateTimeFormatter.ofPattern("MMMM dd,   yyyy");

DateTimeFormatter fmt2  = DateTimeFormatter.ofPattern("MMMM dd,   yyyy", Locale.GERMAN);

DateTimeFormatter class withLocale() method returns a DateTimeFormatter object for the specified locale from the same pattern.

DateTimeFormatter fmt2 = fmt1.withLocale(Locale.GERMAN);

getLocale() method from DateTimeFormatter class returns the locale for current formatter.

Example 2


import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.util.Locale;
/*from w w  w.j a  v a2 s  .  c o  m*/
public class Main {

  public static void main(String[] args) {
    LocalTime lt = LocalTime.of(16, 30, 5, 78899);
    format(lt, "HH:mm:ss");
    format(lt, "KK:mm:ss a");
    format(lt, "[MM-dd-yyyy][' at' HH:mm:ss]");

    ZoneId usCentral = ZoneId.of("America/Chicago");
    ZonedDateTime zdt = ZonedDateTime.of(LocalDate.now(), lt, usCentral);
    format(zdt, "MM/dd/yyyy HH:mm:ssXXX");
    format(zdt, "MM/dd/yyyy VV");
    format(zdt, "[MM-dd-yyyy][' at' HH:mm:ss]");

  }

  public static void format(Temporal co, String pattern) {
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern, Locale.US);
    String str = fmt.format(co);
    System.out.println(pattern + ": " + str);
  }
}

The code above generates the following result.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial