Java 8 –如何格式化LocalDateTime
很少有示例向您展示如何在Java 8中格式化java.time.LocalDateTime
。
1. LocalDateTime + DateTimeFormatter
要格式化LocalDateTime对象,请使用DateTimeFormatter
TestDate1.java
package com.mkyong.time;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TestDate1 {
public static void main(String[] args) {
//Get current date time
LocalDateTime now = LocalDateTime.now();
System.out.println("Before : " + now);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = now.format(formatter);
System.out.println("After : " + formatDateTime);
}
}
输出量
Before : 2016-11-09T11:44:44.797
After : 2016-11-09 11:44:44
2.字符串-> LocalDateTime
将字符串转换为LocalDateTime
另一个示例
TestDate2.java
package com.mkyong.time;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TestDate2 {
public static void main(String[] args) {
String now = "2016-11-09 10:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime formatDateTime = LocalDateTime.parse(now, formatter);
System.out.println("Before : " + now);
System.out.println("After : " + formatDateTime);
System.out.println("After : " + formatDateTime.format(formatter));
}
}
输出量
Before : 2016-11-09 10:30
After : 2016-11-09T10:30
After : 2016-11-09 10:30
参考文献
- DateTimeFormatter JavaDoc
- Java 8 –如何将字符串转换为LocalDate
标签: 日期 格式 java.time java8 localdatetime
翻译自: https://mkyong.com/java8/java-8-how-to-format-localdatetime/
还没有评论,来说两句吧...