在Java中如何格式化输出日期与时间

推荐使用Java 8的dateTimeformatter格式化日期时间,配合LocalDateTime或ZonedDateTime实现安全高效输出,如yyyy-MM-dd HH:mm:ss;2. 传统SimpleDateFormat非线程安全,适用于旧版本。

在Java中如何格式化输出日期与时间

在Java中格式化输出日期与时间,常用的方式是使用 java.time 包中的类(Java 8 及以上推荐)或传统的 SimpleDateFormat。下面介绍几种实用的方法。

使用 DateTimeFormatter(推荐方式)

Java 8 引入了新的日期时间 API,位于 java.time 包中,配合 DateTimeFormatter 可以安全、高效地格式化日期时间。

  • LocalDateTime:表示本地日期时间,无时区信息
  • ZonedDateTime:包含时区的日期时间
  • DateTimeFormatter:用于定义输出格式

示例代码:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);
String formatted = now.format(formatter);
System.out.println(formatted); // 输出如:2025-04-05 14:30:22

常见格式化模式说明

通过 ofPattern() 方法自定义输出样式,常用符号包括:

立即学习Java免费学习笔记(深入)”;

在Java中如何格式化输出日期与时间

比格设计

比格设计是135编辑器旗下一款一站式、多场景、智能化的在线图片编辑器

在Java中如何格式化输出日期与时间124

查看详情 在Java中如何格式化输出日期与时间

  • yyyy:四位年份
  • MM:两位月份(01-12)
  • dd:两位日期(01-31)
  • HH:24小时制小时(00-23)
  • mm:分钟(00-59)
  • ss:秒数(00-59)
  • hh:12小时制小时(01-12)
  • a:上午/下午标记(AM/PM)

例如:

DateTimeFormatter.ofPattern(“yyyy年MM月dd日 HH:mm”)
// 输出:2025年04月05日 14:30

处理时区时间(ZonedDateTime)

如果需要显示带时区的时间,可以使用 ZonedDateTime

import java.time.ZonedDateTime;
import java.time.ZoneId;

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of(“Asia/Shanghai“));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss XXX”);
System.out.println(zdt.format(formatter));
// 输出如:2025-04-05 14:30:22 +08:00

传统方式:SimpleDateFormat(适用于旧版本)

在 Java 8 之前,通常使用 SimpleDateFormatDate 类,但该类不是线程安全的,建议封装或使用 ThreadLocal

import java.text.SimpleDateFormat;
import java.util.Date;

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
System.out.println(sdf.format(date));

基本上就这些。推荐新项目使用 java.timeDateTimeFormatter,更清晰、更安全。根据实际需求选择合适的时间类型和格式模板即可。

暂无评论

发送评论 编辑评论


				
上一篇
下一篇
text=ZqhQzanResources