格式化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 是线程安全的,因此可以在多线程环境下共享使用。

相关推荐
MY_TEUCK7 小时前
【Java 后端】SpringBoot 登录认证与会话跟踪实战(JWT + Filter/Interceptor)
java·开发语言·spring boot
今天长肉了吗7 小时前
银行风控项目踩坑实录:指标跑了6小时,风险评分全挂了
java
QQ2422199797 小时前
基于python+微信小程序的家教管理系统_mh3j9
开发语言·python·微信小程序
随读手机7 小时前
多式联运信息交互平台完整方案(2026版)
java·ai·eclipse·云计算·区块链
沐知全栈开发7 小时前
JavaScript 条件语句
开发语言
RSTJ_16257 小时前
PYTHON+AI LLM DAY THREETY-SEVEN
开发语言·人工智能·python
清水白石0088 小时前
《Python性能深潜:从对象分配开销到“小对象风暴”的破解之道(含实战与最佳实践)》
开发语言·python
Je1lyfish8 小时前
CMU15-445 (2025 Fall/2026 Spring) Project#3 - QueryExecution
linux·c语言·开发语言·数据结构·数据库·c++·算法
许彰午8 小时前
03-二叉树——从递归遍历到非递归实现
java·算法
nj01288 小时前
Spring 循环依赖详解:三级缓存、早期引用、AOP 代理与懒加载
java·spring·缓存