Languages
[Edit]
EN

Java 8 - How to Format LocalDateTime examples

5 points
Created by:
Root-ssh
68600

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join