Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

Java 8 - How to Format LocalDateTime examples

0 contributions
5 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more