Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In computer science, Unix timestamp, also known as epoch time, is a standard way to represent a particular point in time. It denotes the number of seconds that have elapsed since January 1, 1970.

In this tutorial, we’ll shed light on how to convert a classic date into a Unix timestamp. First, we’ll explore how to do this using built-in JDK methods. Then, we’ll illustrate how to achieve the same objective using external libraries such as Joda-Time.

2. Using the Java 8+ Date-Time API

Java 8 introduced a new Date-Time API that we can use to answer our central question. This new API comes with several methods and classes to manipulate dates. So, let’s take a close look at each option.

2.1. Using the Instant Class

In short, the Instant class models an instantaneous point on the timeline. This class provides a straightforward and concise method to get the Unix time from a given date.

So, let’s see it in action:

@Test
void givenDate_whenUsingInstantClass_thenConvertToUnixTimeStamp() {
    Instant givenDate = Instant.parse("2020-09-08T12:16:40Z");

    assertEquals(1599567400L, givenDate.getEpochSecond());
}

As we can see, the Instant class offers the getEpochSecond() method to get the epoch timestamp in seconds from the specified date.

2.2. Using LocalDateTime Class

LocalDateTime is another option to consider when converting a date to epoch time. This class denotes a combination of date and time, often viewed as year, month, day, hour, minute, and second.

Typically, this class provides the toEpochSecond() method to get the epoch time in seconds from the specified date time:

@Test
void givenDate_whenUsingLocalDateTimeClass_thenConvertToUnixTimeStamp() {
    LocalDateTime givenDate = LocalDateTime.of(2023, 10, 19, 22, 45);

    assertEquals(1697755500L, givenDate.toEpochSecond(ZoneOffset.UTC));
}

As shown above, unlike other methods, toEpochSecond() accepts a ZoneOffset object, which allows us to define the fixed offset of the timezone, UTC.

3. Using the Legacy Date API

Alternatively, we can use Date and Calendar classes from the old API to achieve the same outcome. So, let’s go down the rabbit hole and see how to use them in practice.

3.1. Using the Date Class

In Java, the Date class represents a specific point in time with millisecond precision. It provides one of the easiest ways to convert a date into a Unix timestamp through the getTime() method:

@Test
void givenDate_whenUsingDateClass_thenConvertToUnixTimeStamp() throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date givenDate = dateFormat.parse("2023-10-15 22:00:00");

    assertEquals(1697407200L, givenDate.getTime() / 1000);
}

Typically, the method returns the number of milliseconds since the epoch of the passed date. As we can see, we divided the result by 1000 to get the epoch in seconds. However, this class is considered outdated and shouldn’t be used when working with dates.

3.2. Using the Calendar Class

Similarly, we can use the Calendar class from the same package, java.util. This class provides a host of methods to set and manipulate dates.

With Calendar, we have to call getTimeInMillis() to return the Unix time from the specified date:

@Test
void givenDate_whenUsingCalendarClass_thenConvertToUnixTimeStamp() throws ParseException {
    Calendar calendar = new GregorianCalendar(2023, Calendar.OCTOBER, 17);
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));

    assertEquals(1697500800L, calendar.getTimeInMillis() / 1000);
}

Please note that this method, as the name implies, returns the timestamp in milliseconds. The drawback of this choice is that Calendar is declared a de facto legacy since it belongs to the old API.

4. Using Joda-Time

Another solution would be using the Joda-Time library. Before starting working with the library, let’s add its dependency to pom.xml:

<dependency>
    <groupId>joda-time</groupId> 
    <artifactId>joda-time</artifactId> 
    <version>2.12.6</version> 
</dependency>

Joda-Time offers its version of the Instant class that we can use to tackle our challenge. So, let’s illustrate how to use this class using a new test case:

@Test
void givenDate_whenUsingJodaTimeInstantClass_thenConvertToUnixTimeStamp() {
    org.joda.time.Instant givenDate = org.joda.time.Instant.parse("2020-09-08T12:16:40Z");

    assertEquals(1599567400L, givenDate.getMillis() / 1000);
}

As illustrated, the Instant class provides a direct way to get the number of milliseconds since the epoch.

DateTime class is another solution to consider when working with Joda-Time. It offers the getMillis() method to return the number of milliseconds passed since the epoch of the DateTime instant:

@Test
void givenDate_whenUsingJodaTimeDateTimeClass_thenConvertToUnixTimeStamp() {
    DateTime givenDate = new DateTime("2020-09-08T12:16:40Z");

    assertEquals(1599567400L, givenDate.getMillis() / 1000);
}

Unsurprisingly, the test case passed with success.

5. Conclusion

In this short article, we explored different ways of converting a given date into a Unix timestamp.

First, we explained how to do this using core JDK methods and classes. Then, we showcased how to achieve the same objective using Joda-Time.

As always, the code used in this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.