Search code examples
javadatedatetimeformatdatetimeformatter

Pattern.format(date) vs Date.fomat(Pattern)?


I came to know that DateTimeFormatter has two implementation for formatting the date.

  1. Pattern.format(date)

  2. Date.format(pattern)

    public static void main(String[] args) {
         DateTimeFormatter pattern = DateTimeFormatter.ofPattern("MM/dd/yyyy");
         LocalDate date = LocalDate.now();
         String dateFormatText = date.format(pattern);
         String patternFormatText = pattern.format(date); 
         System.out.println(dateFormatText);
         System.out.println(patternFormatText);
    }
    
    

Both the SysOut prints the same value.

The Oracle docs examples uses Date.format method, whereas I can see many tech blogs using the Pattern.format method.

Can anyone explain me what is the difference and which is best to use?

Source Code Demo : Here


Solution

  • Can anyone explain me what is the difference?

    There is no significant difference.

    The javadoc for LocalDateTime.format says:

    public String format(DateTimeFormatter formatter)

    Formats this date-time using the specified formatter.

    This date-time will be passed to the formatter to produce a string.

    In other words, LocalDateTime.format calls DateTimeFormatter.format.


    ... and which is best to use?

    Neither is "best".

    It is up to you decide which form expresses your intention more clearly. Do you want to say:

    • "LocalDateTime: format yourself with this formatter", or
    • "DateTimeFormatter: format this temporal value".