Converting Timestamp to Date in Java

Navigate to:

When working with any programming language, like Java, you’ll have to deal with dates and times now and again. For instance, you might run into a situation where you must convert a timestamp to a date.

In this post, we’ll help you understand the nuances of timestamps and dates in Java. You’ll understand what a timestamp and a date in Java are, when and how to use them, and how to convert one to the other.

What is a timestamp and a date in Java?

To begin, let’s determine the difference between a timestamp and a date in Java. In Java, a timestamp represents a specific instance in time. This instance has a precision of up to nanoseconds. You would typically use timestamps to record events or moments as they occur.

On the other hand, a date in Java usually refers to an instance of java.util.Date. This instance holds the number of milliseconds since the UNIX epoch (Jan. 1, 1970, 00:00:00 GMT). A timestamp gives you an exact moment in time, whereas a date gives you the time elapsed from a specific date.

When should you use timestamp and date?

Now, let’s understand the difference between the two regarding application and usage. You should use a timestamp when you need a precise moment, often down to the nanosecond. This could mean a situation in which you wish to log the exact moment an event occurs in a system.

For example, let’s say you use a backend API to sign up a user and create a record in your user table. This record can have a field called createdOn. This field can be a timestamp representing the exact moment this user record was created.

The createdOn, in turn, represents when the user signed up. In contrast to timestamps, you should use a date when you need to represent a day, month, and year without the need for such high precision. For instance, let’s say you want to show when a user published a blog on your blogging website. You can use the date to represent when the blog was published, and you don’t need a high precision for this.

Converting timestamp to date in Java

Let’s now look at some examples of how to convert a timestamp to a date in Java.

Using the java.sql.Timestamp class

Java offers a java.sql.Timestamp class that you can use to convert a timestamp to a date. This class extends java.util.Date, making the conversion straightforward.

import java.sql.Timestamp;

import java.util.Date;

public class TimestampToDateExample {

` public static void main(String[] args) {`

` // Creating a current timestamp`

` Timestamp timestamp = new Timestamp(System.currentTimeMillis());`

` // Conversion to Date`

` // The getTime() method fetches the time in milliseconds from the UNIX epoch`

` Date date = new Date(timestamp.getTime());`

` // Output the converted date`

` System.out.println(“Date: “ + date);`

` }`

}

In the above code, we use the Timestamp(System.currentTimeMillis())to create a new timestamp representing the current time. Then, we use timestamp.getTime() to retrieve the milliseconds from the UNIX epoch for the timestamp. After that, we use this value to create a Date object. If you run the above code, you should get a new timestamp converted to the current date, as shown below:

Using the java.util.Date class

For a more direct approach, you can also use java.util.Date directly. Here’s an example:

import java.util.Date;

public class CurrentTimestampToDate {

` public static void main(String[] args) {`

` // Current timestamp as milliseconds`

` long currentTimeMillis = System.currentTimeMillis();`

` // Convert to Date`

` Date date = new Date(currentTimeMillis);`

` // Output the date`

` System.out.println(“Date: “ + date);`

` }`

}

In the above code, we use System.currentTimeMillis() to provide the current time in milliseconds since the UNIX epoch. Then, we use these milliseconds to instantiate a Dateobject directly. The above code should give you the same output as shown in the previous example.

Converting a specific timestamp to date

Let’s say that instead of the current timestamp you want to convert a specific timestamp to a date. For this, we can use the same new Timestamp(1672531200000L) method and pass the specific timestamp value to it.

It creates a timestamp for a specific moment (here represented as milliseconds from the UNIX epoch). Like the previous examples, getTime() extracts the milliseconds for a date conversion.

import java.sql.Timestamp;

import java.util.Date;

public class SpecificTimestampToDate {

` public static void main(String[] args) {`

` // Specific timestamp`

` Timestamp specificTimestamp = new Timestamp(1672531200000L);`

` // Convert to Date`

` Date date = new Date(specificTimestamp.getTime());`

` // Output the date`

` System.out.println(“Date: “ + date);`

` }`

}

When you run the above code, you should get the date of that specific timestamp, as shown below:

Time zone awareness in timestamp to date conversion

When dealing with timestamps and dates in Java, understanding time zones is crucial. The primary challenge is that java.util.Date represents time in UTC, but your application might need to display it in different time zones. For instance, let’s say you store the dates in the UTC format, but your users are in the EST timezone. In that case, you might need to display and render the dates in EST format. Let’s see an example where we take the current date and format it to both UTC and EST.

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.TimeZone;

public class TimeZoneExample {

` public static void main(String[] args) {`

` // Timestamp for current time`

` long currentTimeMillis = System.currentTimeMillis();`

` Date currentDate = new Date(currentTimeMillis);`

` // Format the date in UTC`

` SimpleDateFormat sdfUTC = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);`

` sdfUTC.setTimeZone(TimeZone.getTimeZone(“UTC”));`

` System.out.println(“Date in UTC: “ + sdfUTC.format(currentDate));`

` // Format the date in Eastern Standard Time (EST)`

` SimpleDateFormat sdfEST = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);`

` sdfEST.setTimeZone(TimeZone.getTimeZone(“EST”));`

` System.out.println(“Date in EST: “ + sdfEST.format(currentDate));`

` }`

}

We’ve used the approach of the previous example to obtain the current date. Then, we use SimpleDateFormat to format the date in UTC and EST. If you run the above code, you should see the current date printed in both UTC and EST format:

Exception handling in timestamp-to-date conversion

From API calls to data processing to something as simple as date and time conversions, exception handling is a must. Proper exception handling ensures robustness in your code. Let’s see how to handle common exceptions, particularly when dealing with conversions.

Handling NumberFormatException

A common exception related to timestamps is the NumberFormatException. This exception occurs when attempting to convert a string to a numeric format like long, often used in timestamp creation. Here’s an example:

import java.util.Date;

public class ExceptionHandlingExample {

` public static void main(String[] args) {`

` try {`

` String timestampString = “invalidNumber”;`

` long timestamp = Long.parseLong(timestampString);`

` Date date = new Date(timestamp);`

` System.out.println(“Date: “ + date);`

` } catch (NumberFormatException e) {`

` System.err.println(“Invalid timestamp format: “ + e.getMessage());`

` }`

` }`

}

In the above code, we try to parse an invalid string as a long. The NumberFormatException is caught, and an error message is printed. Hence, instead of crashing, the program informs the user of the invalid format. If you run the above code, you should get the error message printed on the console, as shown below:

Handling DateTimeParseException

Another common exception that can occur when parsing date and time strings is the DateTimePaseException. It’s especially common in in the Java 8 time API.

import java.time.Instant;

import java.time.format.DateTimeParseException;

public class DateTimeParseExceptionHandling {

` public static void main(String[] args) {`

` try {`

` String invalidInstant = “2024-01-32T10:15:30.00Z”; // Invalid date`

` Instant parsedInstant = Instant.parse(invalidInstant);`

` System.out.println(“Parsed Instant: “ + parsedInstant);`

` } catch (DateTimeParseException e) {`

` System.err.println(“Failed to parse date-time: “ + e.getMessage());`

` }`

` }`

}

In the above code, we attempt to parse an invalid date-time string to an Instant. Then, we catch the DateTimeParseException in the catch block and report the parsing failure instead of terminating unexpectedly. If you run the above code, you should get the error message printed on the console, as shown below:

Best practices

Here are some best practices to help you get started.

  • If you’re using newer Java versions, use java.time API.
  • Java 8 Time API for any timestamp and date related operations is preferred.
  • Moreover, for robust code and thread safety, try using immutable objects.
  • Also, ensure that you don’t refrain from exception handling, especially when dealing with timestamps and date objects.
  • Finally, be aware of time zones. Not taking into account time zones can cause confusion for your users. Ensure that you consider time zones when calculating, printing, and storing timestamps and date objects.

Conclusion

In this post, we’ve learned how to convert timestamp to date in Java using some practical and meaningful examples. Remember to follow best practices when converting timestamp to date in your next Java project.

This post was written by Siddhant Varma. Siddhant is a full stack JavaScript developer with expertise in frontend engineering. He’s worked with scaling multiple startups in India and has experience building products in the Ed-Tech and healthcare industries.