Java Date Time - Custom Date Format Patterns








The following list shows the formatting symbols we can use to create custom data format patterns.

  • G
    Era
    Example:
        G     AD
        GGGG  Anno Domini
        GGGGG A    
        
  • u
    Year
    It can be a positive or negative number. Year is a positive number After an era start date. Year is a negative number before an era start date. 2014 AD is 2014 and 2014 BC is -2014.
    Example:
            u/uuu/uuuu 2014
            uu         12
            uuuuu      02014
        
  • y
    Year of era
    It counts the year forward or backward from the era start date. It is always a positive number. 2014 AD is 2014 and 2014 BC is 2015. In Common Era, year 0 is 1 BC.
    Example:
        y/yyy/yyyy 2014
        yy         12
        yyyyy      02014
        
  • D
    Day of year (1 -366)
    Example:
    D 150
  • M/L
    Month of year
    Example:
    M    5
    MM   05
    MMM  Jul
    MMMM July
    
  • d
    Day of month
  • Example:
        d    21
        dd   01
        ddd 001
        ddd 029
        
  • Q/q
    Quarter of year
    Example:
        Q      3
        QQ     03
        QQQ    Q3
        QQQQ   3rd quarter
  • Y
    Week-based year
    Example:
        Y        2014
        YY       12
        YYY/YYYY 2014    
        
  • w
    Week of week-based year
    Example:
        w 31
        
  • W
    Week of month
    Example:
    W 2
  • E
  • Day of week
    Example:
        E     7
        EE    07
        EEE   Sun
        EEEEE Sunday
        
  • F
    Day of week in month
    Example:
    F 1
  • a
    AM/PM of day
    Example:
    a AM
  • h
    Clock hour of AM/PM (1-12)
    Example:
    h 2
  • K
    Hour of AM/PM (0-11)
    Example:
    K 3
  • k
    Clock hour of AM/PM (1-24)
    Example:
    k 7
  • H
    Hour of day (0-23)
    Example:
        H 7
        HH 07
        
  • m
    Minute of hour
    Example:
    mm 21
  • s
    Second of minute
    Example:
    ss 12
  • S
    Fraction of second
    Example:
    SSSSSSSSS 000006789
  • A
    Millisecond of day
    Example:
    A 12014012
  • n
    Nanosecond of second
    Example:
    n 789
  • N
    Nanosecond of day
    Example:
    N 12014012001289
  • V
    Time zone ID
    Example:
    VV   America/Chicago
  • z
    Time zone name
    Example:
    z   CDT
  • Z
    Zone offset
    Example:
        Z      -0500
        ZZ     -0500
        ZZZ    -05:00
        ZZZZ   GMT-05:00
        
  • O
    Localized zone offset
    Example:
    O   GMT-5
  • X
    Zone offset
    Example:
            X       +09
            XX      +0930 
            XXX     +09:30
            XXX     -05:00
            XXXX    +093045
            XXXXX   +08:30:45
        
  • x
    Same as X, except that it prints '+00' for the zone offset zero, not 'Z'.
    Example:
    xx -0500
  • p
    pads the pattern with spaces. The number of p determines the width of the output.
    Example:
        mm      30
        pppmm " 30"
    
  • '
    Escape for text.
    Text within single quotes is output directly.
    To output a single quote, use two consecutive single quotes.
    Example:
    'Hello' MMMM     Hello July
  • ''
    A single quote
    Example:
    '''Hello''' MMMM             'Hello' July
  • []
    The symbols [ and ] marks an optional section. A pattern enclosed within an optional section is output only if information is available for all its elements.
  • #, {, }
    reserved for future use.




Example

import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.util.Locale;
/*from www.  java  2  s .com*/
public class Main {

  public static void main(String[] args) {
    LocalDate ld = LocalDate.of(2014, Month.JUNE, 30);
    format(ld, "M/d/yyyy");
    format(ld, "MM/dd/yyyy");
    format(ld, "MMM   dd,   yyyy");
    format(ld, "MMMM   dd,   yyyy");
    format(ld, "EEEE, MMMM   dd,   yyyy");
    format(ld, "'Month' q  'in' QQQ");
  }

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

The code above generates the following result.





Custom Date Format with Locale

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)

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 www  .j a va2s.co  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.

Custom Date Format with Optional

When defining custom date time format we can use symbols [ and ] to mark an optional section.

A pattern enclosed within an optional section is output only if information is available for all its elements.

The following code shows how to use an optional format.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
/* w w  w.  j a  v  a2 s. c om*/
public class Main {

  public static void main(String[] args) {
    String pattern = "MM/dd/yyyy[ 'at' HH:mm:ss]";
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);

    LocalDate ld = LocalDate.of(2014, Month.JUNE, 30);
    LocalTime lt = LocalTime.of(17, 30, 12);
    LocalDateTime ldt = LocalDateTime.of(ld, lt);

    String str1 = fmt.format(ld);
    System.out.println(str1);

    String str2 = fmt.format(ldt);

    System.out.println(str2);
  }
}

The code above generates the following result.

Java DateTimeFormatterBuilder

We can create custom date time formatter from DateTimeFormatterBuilder.

The following code builds a DateTimeFormatter object to format a date in the format like "New Year in YEAR is on WEEK_DAY":

import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
/*  w w w  .  java  2s  . c om*/
public class Main {

  public static void main(String[] args) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendLiteral("New Year in ")
    .appendValue(ChronoField.YEAR)
    .appendLiteral(" is  on  ")
    .appendText(ChronoField.DAY_OF_WEEK,TextStyle.FULL_STANDALONE)
    .toFormatter(); 
    LocalDate ld  = LocalDate.of(2014, Month.JANUARY, 1); 
    String str = ld.format(formatter); 
    System.out.println(str);

  }
}

The code above generates the following result.

Example 3

We can create the same custom formatter using a pattern from DateTimeFormatterBuilder.

import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
//  w w w  .  j av a 2s  .c om
public class Main {

  public static void main(String[] args) {
    LocalDate ld  = LocalDate.of(2014,Month.JANUARY,1);
    String pattern = "'New Year in'  yyyy  'is on' EEEE"; 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); 
    String str = ld.format(formatter);
    System.out.println(str); 

  }
}

The code above generates the following result.