Languages
[Edit]
EN

Java 8 - How to Format LocalDateTime examples

5 points
Created by:
Root-ssh
175450

1. Overview

In this post we cover basic usage of LocalDateTime class introduced in Java 8.

2. LocalDateTime with DateTimeFormatter

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

public class Example1 {

    public static void main(String[] args) {

        LocalDateTime localDateTime = LocalDateTime.now();

        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String format = localDateTime.format(formatter);

        System.out.println("LocalDateTime.now: ");
        System.out.println(localDateTime);
        System.out.println("Formatted: ");
        System.out.println(format);
    }
}

Output:

LocalDateTime.now:
2019-10-13T12:19:26.665
Formatted:
2019-10-13 12:19:26

3. String to LocaDateTime

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

public class Example2 {

    public static void main(String[] args) {

        String dateTime = "2019-10-13 12:19:26";

        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime localDateTime = LocalDateTime.parse(dateTime, formatter);

        System.out.println("LocalDateTime: ");
        System.out.println(localDateTime);
    }
}

Output:

LocalDateTime:
2019-10-13T12:19:26

4. String to LocaDateTime with build-in formatter

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

public class Example3 {

    public static void main(String[] args) {

        String dateTime = "2019-10-13T12:19:26.541";

        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        LocalDateTime localDateTime = LocalDateTime.parse(dateTime, formatter);

        System.out.println("LocalDateTime: ");
        System.out.println(localDateTime);
    }
}

Output:

LocalDateTime:
2019-10-13T12:19:26.541

References

  1. LocalDateTime - JavaDoc
  2. DateTimeFormatter - JavaDoc
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join