Languages
[Edit]
EN

Java 8 - How to Format LocalDateTime examples

5 points
Created by:
Root-ssh
6340

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
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.