格式化LocalDateTime为字符串代码示例

在使用 LocalDateTime 进行时间格式化时,可以使用 DateTimeFormatter 类来实现。以下是一个将当前时间格式化为 "yyyy-MM-dd HH:mm:ss" 的示例代码:

java 复制代码
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("Formatted date/time: " + formattedDateTime);
    }
}

上述代码中, DateTimeFormatter 的 ofPattern 方法用于指定日期时间格式,与 SimpleDateFormat 中的格式字符串类似。然后,使用 LocalDateTime 的 format 方法将当前时间格式化为指定格式的字符串。

注意, DateTimeFormatter 是线程安全的,因此可以在多线程环境下共享使用。

相关推荐
Flynn Liang14 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型
吃我一窝jio15 小时前
Python与Go线程模型深度对比
java·开发语言·python
这个昵称不容易15 小时前
SpringBoot 购物推荐网站的设计与实现:120 个 Java 文件、147 个接口、13 张表,附真实运行截图
java·springboot·毕设
文丑颜不良啊15 小时前
LeetCode3041~3060题目解析
java·leetcode
eggwyw15 小时前
C++ union 的一种妙用法
开发语言·c++
文丑颜不良啊17 小时前
LeetCode3101~3120题目解析
java·leetcode
Resean022317 小时前
SpringMVC 6+源码分析(十一)视图渲染与异步请求(收尾篇)
java·spring·springmvc
starzy199017 小时前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
靠沿18 小时前
MySQL数据库进阶——存储过程和触发器
java·数据库·mysql
码少女18 小时前
MySQL--库与表的增删改查基础
java·数据库·mysql