Java Instant to Date and vice versa

In this post I am going to show exactly how to convert Instant to Date and vice versa.

I will use code examples to make things clear!

Let’s get started!

Java Instant to Date

Instant class is designed to represent specific point in time with nanosecond precision in coordinated universal time (UTC).

There may be scenarios in your project where you may want to convert Instant to Date for legacy use cases.

In below example we create an Instant object and pass the object as an argument to Date.from()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import java.time.Instant;
import java.util.Date;

public class InstantDemo {


    public static void main(String[] args) {

        Instant instant = Instant.now();
        System.out.println("Instant: "+instant);

        Date date = Date.from(instant);
        System.out.println("Date: "+date);

    }
}

Output:

1
2
Instant: 2023-09-09T10:25:19.407856700Z
Date: Sat Sep 09 15:55:19 IST 2023

Java Date to Instant

Let us see the scenario where we need to convert date to Instant.

This is most likely used scenario in your project because we are moving from legacy to Instant which is recommended.

Just call toInstant() method in Date object to get Instant.

Checkout below example as shown below

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;

public class InstantDemo {


    public static void main(String[] args) {

        Date date = Calendar.getInstance().getTime();
        System.out.println("Date is: "+date);

        Instant instant = date.toInstant();
        System.out.println("Instant is: " +instant);

    }
}
1
2
Date is: Sat Sep 09 16:10:35 IST 2023
Instant is: 2023-09-09T10:40:35.406Z