Avoid Date Bugs: Thread‑Safe Formatting and Time‑Zone Mastery in Java
This article explores common pitfalls in Java date handling—such as non‑thread‑safe formatting and daylight‑saving‑time errors—and presents robust solutions using ThreadLocal, the Java 8 Date/Time API, zone‑aware calculations, caching, and global interceptor patterns to ensure correct, high‑performance time processing in backend systems.
Introduction
In everyday development we often deal with various date formats (e.g., 2025-04-21, 2025/04/21, 2025年04月21日) and different data types (String, Date, Long). Improper conversion between these types can cause unexpected bugs.
1. Date Pitfalls
1.1 Formatting Trap
A classic issue is using a shared SimpleDateFormat in a multithreaded environment, which can produce impossible dates like 2023-02-30 12:00:00 under high concurrency.
public class OrderService {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void saveOrder(Order order) {
// Concurrent threads may corrupt the internal Calendar
String createTime = sdf.format(order.getCreateTime());
orderDao.insert(createTime);
}
}The root cause is that SimpleDateFormat internally shares a mutable Calendar instance, which gets corrupted when accessed by multiple threads.
1.2 Time‑Zone Conversion
Naïvely adding eight hours to convert UTC to Beijing time ignores daylight‑saving‑time (DST) transitions, leading to errors such as a sudden jump back to 01:00 on 2024‑10‑27.
public Date convertToBeijingTime(Date utcDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(utcDate);
cal.add(Calendar.HOUR, 8); // DST not considered
return cal.getTime();
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
