在Java中,日期格式化是将Date
对象或时间戳转换为特定格式的字符串表示,或者将格式化的日期字符串解析为Date
对象的过程。Java提供了多种方式来处理日期格式化。
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
// 创建SimpleDateFormat对象并指定格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 格式化当前日期
String formattedDate = sdf.format(new Date());
System.out.println("当前时间: " + formattedDate);
// 解析日期字符串
try {
Date parsedDate = sdf.parse("2023-05-15 14:30:00");
System.out.println("解析后的日期: " + parsedDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
public static void main(String[] args) {
// 创建DateTimeFormatter对象
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化当前日期
LocalDateTime now = LocalDateTime.now();
String formattedDate = now.format(formatter);
System.out.println("当前时间: " + formattedDate);
// 解析日期字符串
LocalDateTime parsedDate = LocalDateTime.parse("2023-05-15 14:30:00", formatter);
System.out.println("解析后的日期: " + parsedDate);
}
}
| 符号 | 含义 | 示例 | |------|---------------------|----------| | y | 年 | yyyy → 2023 | | M | 月 | MM → 05 | | d | 日 | dd → 15 | | H | 小时(0-23) | HH → 14 | | h | 小时(1-12, AM/PM) | hh → 02 | | m | 分钟 | mm → 30 | | s | 秒 | ss → 45 | | S | 毫秒 | SSS → 789 | | E | 星期几 | E → 周一 | | a | AM/PM标记 | a → 下午 |
原因:SimpleDateFormat不是线程安全的,多线程共享同一个实例会导致问题。
解决方案:
// ThreadLocal解决方案
private static final ThreadLocal<SimpleDateFormat> threadLocalSdf =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
原因:未明确指定时区可能导致不同环境下的解析结果不同。
解决方案:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 明确设置时区
// Java 8方式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.of("Asia/Shanghai"));
原因:输入字符串与格式模式不匹配。
解决方案:
try {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2023/05/15");
} catch (ParseException e) {
System.out.println("日期格式不匹配");
}
java.time
包中的类