Java 8中如何格式化LocalDateTime呢?
下文笔者讲述格式化LocalDateTime的方法分享,如下所示
LocalDateTime对象格式化
格式化LocalDateTime方法
实现思路: 使用DateTimeFormatter即可格式化LocalDateTime对象例:
LocalDateTime对象格式化
package com.java265.time; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class TestClass { public static void main(String[] args) { //获取当前时间 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); } } //字符串转换为LocalDateTime package com.java265.time; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class TestDate2 { public static void main(String[] args) { String now = "2023-02-02 17:15"; 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)); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。