Languages
[Edit]
EN

Java - convert Instant to Date

5 points
Created by:
Root-ssh
6750

In this short article we would like to show how to convert Instant to Date in Java.

Quick solution:

Date date = Date.from( Instant.now() );
// or
Date date = Date.from( Instant.parse("2020-09-15T18:34:40Z") );

Example 1

Here we have full code example.

import java.time.Instant;
import java.util.Date;

public class Example1 {

    public static void main(String[] args) {

        Instant instant = Instant.now();
        Date date = Date.from(instant);

        System.out.println(date);
    }
}

Output:

Wed Sep 16 13:26:58 CEST 2020

Example 2

Here we have similar example to the previous one, but we get Instant from date time in String. From the documentation we can see that we need to provide date time String in UTC format. Documentation:

Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z. The string must represent a valid instant in UTC and is parsed using DateTimeFormatter.ISO_INSTANT.

import java.time.Instant;
import java.util.Date;

public class Example2 {

    public static void main(String[] args) {

        Instant instant = Instant.parse("2020-09-15T18:34:40Z");
        Date date = Date.from(instant);

        System.out.println(date);
    }
}

Output:

Tue Sep 15 20:34:40 CEST 2020

CEST means Central European Summer Time. We can read more here.

It corresponds to UTC+02:00, which makes it the same as Eastern European Time, Central Africa Time, South African Standard Time and Kaliningrad Time in Russia.

That's why we see 2h difference between parsed date time String and output String. If you run the example on your PC and you are located in different UTC zone, then the output will be different depending on the UTC zone.

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.