Java LocalDateTime 格式化返回给前端 - 示例代码
要将 Java LocalDateTime 对象返回给前端时,可以使用 DateTimeFormatter 类来指定返回的日期时间格式。以下是一个示例:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
// 指定日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss');
// 格式化日期时间对象
String formattedDateTime = now.format(formatter);
System.out.println(formattedDateTime);
// 返回给前端
}
}
在上面的代码中,我们使用 DateTimeFormatter 类的 ofPattern() 方法来指定日期时间的格式。然后,使用 LocalDateTime 对象的 format() 方法将其格式化为指定格式的字符串。
你可以根据自己的需求修改日期时间格式的模式字符串,例如 'yyyy-MM-dd' 表示年-月-日,'HH:mm:ss' 表示小时:分钟:秒等。
最后,你可以将格式化后的日期时间字符串返回给前端。具体如何返回给前端取决于你使用的是什么框架或技术。
原文地址: https://www.cveoy.top/t/topic/pmzY 著作权归作者所有。请勿转载和采集!