EN
Java 8 - How to Format LocalDateTime examples
5 points
In this post we cover basic usage of LocalDateTime class introduced in Java 8.
xxxxxxxxxx
1
import java.time.LocalDateTime;
2
import java.time.format.DateTimeFormatter;
3
4
public class Example1 {
5
6
public static void main(String[] args) {
7
8
LocalDateTime localDateTime = LocalDateTime.now();
9
10
String pattern = "yyyy-MM-dd HH:mm:ss";
11
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
12
String format = localDateTime.format(formatter);
13
14
System.out.println("LocalDateTime.now: ");
15
System.out.println(localDateTime);
16
System.out.println("Formatted: ");
17
System.out.println(format);
18
}
19
}
Output:
xxxxxxxxxx
1
LocalDateTime.now:
2
2019-10-13T12:19:26.665
3
Formatted:
4
2019-10-13 12:19:26
xxxxxxxxxx
1
import java.time.LocalDateTime;
2
import java.time.format.DateTimeFormatter;
3
4
public class Example2 {
5
6
public static void main(String[] args) {
7
8
String dateTime = "2019-10-13 12:19:26";
9
10
String pattern = "yyyy-MM-dd HH:mm:ss";
11
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
12
LocalDateTime localDateTime = LocalDateTime.parse(dateTime, formatter);
13
14
System.out.println("LocalDateTime: ");
15
System.out.println(localDateTime);
16
}
17
}
Output:
xxxxxxxxxx
1
LocalDateTime:
2
2019-10-13T12:19:26
xxxxxxxxxx
1
import java.time.LocalDateTime;
2
import java.time.format.DateTimeFormatter;
3
4
public class Example3 {
5
6
public static void main(String[] args) {
7
8
String dateTime = "2019-10-13T12:19:26.541";
9
10
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
11
LocalDateTime localDateTime = LocalDateTime.parse(dateTime, formatter);
12
13
System.out.println("LocalDateTime: ");
14
System.out.println(localDateTime);
15
}
16
}
Output:
xxxxxxxxxx
1
LocalDateTime:
2
2019-10-13T12:19:26.541