10 Common Java Date API Pitfalls and How to Avoid Them
This article lists ten frequent mistakes when using Java's date and time APIs—such as misusing Calendar fields, wrong format patterns, thread‑unsafe SimpleDateFormat, and daylight‑saving quirks—and provides clear corrected examples and best‑practice solutions.
1. Calendar.set() hour field pitfall
Using Calendar.HOUR sets the hour in 12‑hour mode, which can produce unexpected results (e.g., setting 10 yields 22). The correct field is Calendar.HOUR_OF_DAY for 24‑hour mode.
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 10);
System.out.println(c.getTime());2. Using "YYYY" in SimpleDateFormat
The pattern "YYYY" calculates the week‑based year, causing dates like 2019‑12‑31 to be formatted as 2020‑12‑31. Use lower‑case "yyyy" for the calendar year.
SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dtf.format(testDate));3. Using "hh" instead of "HH"
Pattern "hh" is 12‑hour format; when the hour is 12 it becomes 0. Use "HH" for 24‑hour format.
String str = "2020-03-18 12:00";
SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date newDate = dtf.parse(str);
System.out.println(newDate);4. Calendar month index starts at 0
Calendar months are zero‑based (January = 0). Add 1 when displaying the month.
Calendar calendar = Calendar.getInstance();
System.out.println("Current " + (calendar.get(Calendar.MONTH) + 1) + " month");5. Using "DD" instead of "dd"
Upper‑case "DD" represents the day of year, while lower‑case "dd" is the day of month. Use "dd" for month‑day formatting.
SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dtf.format(testDate));6. SimpleDateFormat format initialization
Calling format() with a raw integer (e.g., 20200323) fails because SimpleDateFormat expects a Date object.
Calendar calendar = Calendar.getInstance();
calendar.set(2020, Calendar.MARCH, 23);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(calendar.getTime()));7. DateTimeFormatter locale issue
Parsing English date strings with the default locale (e.g., Chinese) throws an exception. Supply Locale.US to the formatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss yyyy", Locale.US);
LocalDateTime dateTime = LocalDateTime.parse(dateStr, formatter);
System.out.println(dateTime);8. SimpleDateFormat precision limitation
SimpleDateFormat can only parse strings that match or exceed its defined pattern precision; parsing a shorter string (e.g., "2020-03" with pattern "yyyy-MM-dd") throws a ParseException. Use a matching pattern like "yyyy-MM".
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
System.out.println(sdf.parse("2020-03"));9. SimpleDateFormat thread‑safety
A shared SimpleDateFormat instance is not thread‑safe because it holds a mutable Calendar. Resolve by using a local instance, ThreadLocal, or synchronizing access.
private static final ThreadLocal<DateFormat> threadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public static String formatDate(Date date) throws ParseException {
return threadLocal.get().format(date);
}10. Daylight‑saving time effect
When the default time zone observes DST (e.g., China in 1986), parsing a time like "1986-05-04 00:30:00" may be shifted by one hour. Set the time zone to GMT+8 to obtain the expected result.
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.parse("1986-05-04 00:30:00"));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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
