Languages
[Edit]
EN

Java - convert Instant to Date

5 points
Created by:
Root-ssh
175460

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.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join