159

I can convert a java.util.Date to a java.time.Instant (Java 8 and later) this way:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 8);
cal.set(Calendar.MINUTE, 30);
Date startTime = cal.getTime();
Instant i = startTime.toInstant();

Can anybody let me know about the convert that instant to date with a specific date & time format? i.e 2015-06-02 8:30:00

I have gone through api but could not find a satisfactory answer.

uraimo
  • 19,081
  • 8
  • 48
  • 55
hari m
  • 1,715
  • 2
  • 10
  • 7
  • do you want a `String` output with `yyyy-MM-dd H:m:s`? – Blip Jun 02 '15 at 10:13
  • Is there any particular reason to get the instant from Calendar? and not using the LocalDate or other java.time classes? You are using calendar you can do the Calendar.getTime() which will return the Date instance. Which you can later convert to any format – Bilbo Baggins Jun 02 '15 at 10:27
  • actually from client i get only instant object.. now i need to store the date and time of instant in database. – hari m Jun 02 '15 at 10:56

3 Answers3

355

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);
uraimo
  • 19,081
  • 8
  • 48
  • 55
  • 10
    Use `DateTimeFormatter` instead of `SimpleDateFormat` as it is not thread safe. I have faced some issue in past because of this. More details [here](https://stackoverflow.com/questions/4021151/java-dateformat-is-not-threadsafe-what-does-this-leads-to) – ms_27 Nov 26 '19 at 15:10
  • 2
    Date and SimpleDateFormat are old pre java8 implementation, It should be avoided. The not thread safe thing is one of the problem, the non management of time zone and ofset is another one. But if you really want to face a time zone bug then stick to old Date implementation. – pdem May 20 '21 at 13:13
  • 5
    Whenever saying "such and such should be avoided", try to provide the alternatives. – John Fantastico May 26 '21 at 14:00
  • Can we force the Date.From to be UTC? Thanks – AXMIM Aug 17 '22 at 15:43
  • Date.from(instant) will give java.lang.IllegalArgumentException: java.lang.ArithmeticException: long overflow in case instant is Instant.MAX – Joy May 07 '23 at 05:46
32

An Instant is what it says: a specific instant in time - it does not have the notion of date and time (the time in New York and Tokyo is not the same at a given instant).

To print it as a date/time, you first need to decide which timezone to use. For example:

System.out.println(LocalDateTime.ofInstant(i, ZoneOffset.UTC));

This will print the date/time in iso format: 2015-06-02T10:15:02.325

If you want a different format you can use a formatter:

LocalDateTime datetime = LocalDateTime.ofInstant(i, ZoneOffset.UTC);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(datetime);
System.out.println(formatted);
assylias
  • 321,522
  • 82
  • 660
  • 783
3

try Parsing and Formatting

Take an example Parsing

String input = ...;
try {
    DateTimeFormatter formatter =
                      DateTimeFormatter.ofPattern("MMM d yyyy");
    LocalDate date = LocalDate.parse(input, formatter);
    System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
    System.out.printf("%s is not parsable!%n", input);
    throw exc;      // Rethrow the exception.
}

Formatting

ZoneId leavingZone = ...;
ZonedDateTime departure = ...;

try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
    String out = departure.format(format);
    System.out.printf("LEAVING:  %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
    System.out.printf("%s can't be formatted!%n", departure);
    throw exc;
}

The output for this example, which prints both the arrival and departure time, is as follows:

LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)

For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html

Saket Mittal
  • 3,726
  • 3
  • 29
  • 49