Java DateTimeFormatter Predefined Style

Description

Java DateTimeFormatter Predefined Style

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

public class Main {
  public static void main(String[] args) {
    LocalDate ld = LocalDate.now();
    LocalTime lt = LocalTime.now();
    LocalDateTime ldt = LocalDateTime.now();

    DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
    System.out.println("Formatter Default Locale: " + fmt.getLocale());
    System.out.println("Short Date: " + fmt.format(ld));

    fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
    System.out.println("Medium Date: " + fmt.format(ld));

    fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
    System.out.println("Long Date: " + fmt.format(ld));

    fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
    System.out.println("Full Date: " + fmt.format(ld));

    fmt = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
    System.out.println("Short Time: " + fmt.format(lt));

    fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
    System.out.println("Short Datetime: " + fmt.format(ldt));

    fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
    System.out.println("Medium Datetime: " + fmt.format(ldt));

    // Use German locale to format the date time in MEDIUM style
    fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(
        Locale.GERMAN);/*  w  ww .j a v a2  s. co  m*/
    System.out.println("German Medium Datetime: " + fmt.format(ldt));

    // Use Indian(English) locale to format date time in short style
    fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(
        new Locale("en", "IN"));
    System.out.println("Indian(en) Short Datetime: " + fmt.format(ldt));

    // Use Indian(English) locale to format date time in medium style
    fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(
        new Locale("en", "IN"));
    System.out.println("Indian(en) Medium Datetime: " + fmt.format(ldt));

  }
}



PreviousNext

Related