Languages
[Edit]
EN

Java 8 - how to format LocalDateTime.now() with different formatters

5 points
Created by:
Kate_C
2857

1. Overview

Below we have examples of how to use LocalDateTime.now() with custom date time format patterns.

2. LocalDateTime.now() custom format with DateTimeFormatter.ofPattern

Code example:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeCustomFormatterExample {

    public static void main(String[] args) {

        System.out.println("# Example 1 - default formatter");
        // 2019-10-12T16:09:25.274
        System.out.println(LocalDateTime.now());

        System.out.println("# Example 2");
        // 2019:10:12 16:09:25
        System.out.println(DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ss")
                .format(LocalDateTime.now()));

        System.out.println("# Example 3");
        // 2019:10:12 16:09:25:293
        System.out.println(DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ss:SSS")
                .format(LocalDateTime.now()));

        System.out.println("# Example 4");
        // 20191012_160925294
        System.out.println(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmssSSS")
                .format(LocalDateTime.now()));

        System.out.println("# Example 5");
        // 2019_10_12__16_09_25
        System.out.println(DateTimeFormatter.ofPattern("yyyy_MM_dd__HH_mm_ss")
                        .format(LocalDateTime.now()));

        System.out.println("# Example 6");
        // 2019_10_12__16_09_25_294
        System.out.println(DateTimeFormatter.ofPattern("yyyy_MM_dd__HH_mm_ss_SSS")
                .format(LocalDateTime.now()));
    }
}

Output: 

# Example 1 - default formatter
2019-10-12T16:09:25.274
# Example 2
2019:10:12 16:09:25
# Example 3
2019:10:12 16:09:25:293
# Example 4
20191012_160925294
# Example 5
2019_10_12__16_09_25
# Example 6
2019_10_12__16_09_25_294

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.