Two Methods for Converting Date Strings to Epoch Timestamps in Java

Dec 01, 2025 · Programming · 12 views · 7.8

Keywords: Java | Date Conversion | Epoch Timestamp | SimpleDateFormat | DateTimeFormatter

Abstract: This article provides a comprehensive guide to converting date strings with milliseconds and timezone information to epoch timestamps in Java. It covers two primary approaches: using the legacy SimpleDateFormat class and the modern DateTimeFormatter class introduced in Java 8. The article begins by analyzing the format of the date string "Jun 13 2003 23:11:52.454 UTC", then demonstrates step-by-step implementations of both methods, including pattern string construction, date object parsing, and timestamp extraction. Through comparative analysis, it highlights the advantages of the Java 8 API in terms of type safety, thread safety, and extended functionality, while providing complete code examples and best practice recommendations.

Date String Format Analysis

In Java programming, handling date-time data is a common requirement. The date string discussed in this article, "Jun 13 2003 23:11:52.454 UTC", has the following characteristics: month in English abbreviation (Jun), two-digit day (13), four-digit year (2003), time including hours, minutes, seconds, and milliseconds (23:11:52.454), and finally the timezone specification (UTC). This format requires precise pattern strings for parsing.

Traditional Method Using SimpleDateFormat

Prior to Java 8, java.text.SimpleDateFormat was the primary class for date formatting. The following code demonstrates how to use this class to convert a date string to an epoch timestamp:

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // Output: 1055545912454

Code explanation:

  1. Pattern String Construction: "MMM dd yyyy HH:mm:ss.SSS zzz" precisely matches the input string format. Here, MMM represents the abbreviated month name, dd the two-digit day, yyyy the four-digit year, HH the hour in 24-hour format, mm the minutes, ss the seconds, SSS the milliseconds, and zzz the timezone abbreviation.
  2. Date Parsing: The df.parse(str) method parses the string into a java.util.Date object. This method may throw a ParseException, so exception handling should be added in practical applications.
  3. Timestamp Extraction: date.getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT, i.e., the epoch timestamp.

It is important to note that the SimpleDateFormat class is not thread-safe. In multi-threaded environments, synchronization measures or creating separate instances for each thread are necessary.

Modern Method Using Java 8 DateTimeFormatter

Java 8 introduced a new date-time API (java.time package), where the DateTimeFormatter class provides more powerful and thread-safe date formatting capabilities. Here is an example using this API:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class DateConversionExample {
    public static void main(String[] args) {
        String strDate = "Jun 13 2003 23:11:52.454 UTC";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
        ZonedDateTime zdt = ZonedDateTime.parse(strDate, dtf);
        System.out.println(zdt.toInstant().toEpochMilli()); // Output: 1055545912454
    }
}

Code explanation:

  1. Pattern String: The pattern string is similar to that used with SimpleDateFormat, but DateTimeFormatter employs a more consistent syntax.
  2. Date Parsing: ZonedDateTime.parse(strDate, dtf) directly parses the string into a ZonedDateTime object, which contains complete date, time, and timezone information.
  3. Timestamp Extraction: zdt.toInstant().toEpochMilli() first converts the ZonedDateTime to an Instant (representing a point on the timeline), then retrieves the millisecond timestamp.

Method Comparison and Best Practices

Both methods correctly convert date strings to epoch timestamps, but there are significant differences:

For new projects, it is recommended to use Java 8's DateTimeFormatter. If older Java versions must be used, the thread safety issues of SimpleDateFormat should be addressed. Additionally, exception handling should always be considered during parsing, and input string formats should be validated against expectations.

In practical applications, more flexible patterns can be created using DateTimeFormatterBuilder, or predefined formatters (e.g., DateTimeFormatter.ISO_ZONED_DATE_TIME) can be utilized. These advanced features make the Java 8 API a powerful tool for handling complex date-time requirements.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.