Last Updated: 

Java Convert Long Time to String

In Java, dealing with time and date is a common requirement in many applications. A long value often represents a timestamp in milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). Converting this long time to a human-readable string is a frequent task, which can be useful for logging, displaying information to users, or generating reports. In this blog post, we will explore different ways to convert a long time to a string in Java, including core concepts, typical usage scenarios, common pitfalls, and best practices.

Table of Contents#

  1. Core Concepts
  2. Typical Usage Scenarios
  3. Different Approaches to Convert Long Time to String
    • Using SimpleDateFormat
    • Using DateTimeFormatter (Java 8+)
  4. Common Pitfalls
  5. Best Practices
  6. Conclusion
  7. FAQ
  8. References

Core Concepts#

  • Unix Epoch: The Unix epoch is the time 00:00:00 UTC on January 1, 1970. A long value representing time usually counts the number of milliseconds passed since this moment.
  • Date and Time Formats: Different applications may require different date and time formats, such as "yyyy - MM - dd HH:mm:ss", "MM/dd/yyyy", etc. Java provides classes to format dates and times according to these patterns.

Typical Usage Scenarios#

  • Logging: When logging events, it is often necessary to record the timestamp in a human-readable format. For example, a log entry might show "2024 - 01 - 15 10:30:00" instead of a raw long timestamp.
  • User Interface: Displaying timestamps in a user-friendly way on web or desktop applications. For instance, showing the creation time of a post as "January 15, 2024" in a blog application.
  • Data Export: When exporting data to a CSV or Excel file, converting timestamps to strings can make the data more understandable for end-users.

Different Approaches to Convert Long Time to String#

Using SimpleDateFormat#

SimpleDateFormat is a legacy class in Java for formatting and parsing dates. Here is an example:

import java.text.SimpleDateFormat;
import java.util.Date;
 
public class LongToDateUsingSimpleDateFormat {
    public static void main(String[] args) {
        // A long value representing a timestamp in milliseconds
        long timestamp = 1642254000000L;
 
        // Create a SimpleDateFormat object with the desired format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        // Create a Date object from the long timestamp
        Date date = new Date(timestamp);
 
        // Format the Date object to a string
        String dateString = sdf.format(date);
 
        System.out.println("Formatted date: " + dateString);
    }
}

In this code:

  • We first define a long timestamp.
  • Then we create a SimpleDateFormat object with the format pattern "yyyy - MM - dd HH:mm:ss".
  • We convert the long timestamp to a Date object.
  • Finally, we use the format method of SimpleDateFormat to convert the Date object to a string.

Using DateTimeFormatter (Java 8+)#

DateTimeFormatter is a more modern and thread-safe alternative to SimpleDateFormat introduced in Java 8. Here is an example:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
 
public class LongToDateUsingDateTimeFormatter {
    public static void main(String[] args) {
        // A long value representing a timestamp in milliseconds
        long timestamp = 1642254000000L;
 
        // Create an Instant object from the long timestamp
        Instant instant = Instant.ofEpochMilli(timestamp);
 
        // Convert the Instant object to a LocalDateTime object in the system's default time zone
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
 
        // Create a DateTimeFormatter object with the desired format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
 
        // Format the LocalDateTime object to a string
        String dateString = localDateTime.format(formatter);
 
        System.out.println("Formatted date: " + dateString);
    }
}

In this code:

  • We start by creating an Instant object from the long timestamp.
  • Then we convert the Instant object to a LocalDateTime object in the system's default time zone.
  • Next, we create a DateTimeFormatter object with the desired format pattern.
  • Finally, we use the format method of LocalDateTime to convert it to a string.

Common Pitfalls#

  • Thread Safety: SimpleDateFormat is not thread-safe. If multiple threads access the same SimpleDateFormat object simultaneously, it can lead to incorrect results or NumberFormatException. In contrast, DateTimeFormatter is thread-safe.
  • Locale and Time Zone: SimpleDateFormat and DateTimeFormatter can be affected by the default locale and time zone. If not specified correctly, it can lead to unexpected results. For example, the date format might vary depending on the user's locale.
  • Pattern Syntax: Incorrect pattern syntax in SimpleDateFormat or DateTimeFormatter can cause IllegalArgumentException. For example, using an invalid character in the format pattern.

Best Practices#

  • Use DateTimeFormatter: For Java 8 and later, prefer DateTimeFormatter over SimpleDateFormat due to its thread-safety and improved API.
  • Specify Locale and Time Zone: Always specify the locale and time zone explicitly to avoid issues related to default settings. For example, when using DateTimeFormatter, you can use methods like withLocale and withZone to set the desired locale and time zone.
  • Error Handling: When using SimpleDateFormat or DateTimeFormatter, handle potential exceptions such as IllegalArgumentException and ParseException properly in your code.

Conclusion#

Converting a long time to a string in Java is a common task with multiple approaches. While SimpleDateFormat is a legacy option, DateTimeFormatter provides a more modern, thread-safe, and robust solution. Understanding the core concepts, typical usage scenarios, common pitfalls, and best practices can help you choose the right approach and write reliable code.

FAQ#

Q: Can I use SimpleDateFormat in a multi-threaded environment?#

A: It is not recommended. SimpleDateFormat is not thread-safe. In a multi-threaded environment, use DateTimeFormatter instead.

Q: What if the long timestamp is in seconds instead of milliseconds?#

A: You need to multiply the long value by 1000 to convert it from seconds to milliseconds before using it with Date or Instant classes.

Q: How can I change the time zone when using DateTimeFormatter?#

A: You can use the withZone method of DateTimeFormatter to specify the desired time zone. For example:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("America/New_York"));

References#