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

相关推荐
HerayChen1 小时前
HbuilderX 内存溢出报错
java·大数据·linux
diegoXie1 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条1 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle2 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
小马爱打代码2 小时前
Spring AI:搭建自定义 MCP Server:获取 QQ 信息
java·人工智能·spring
郭涤生2 小时前
QT 架构笔记
java·数据库·系统架构
daidaidaiyu2 小时前
基于LangGraph开发复杂智能体学习一则
java·ai
失散132 小时前
Python——1 概述
开发语言·python
萧鼎2 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法
小小8程序员2 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++