Instant instant = ...; String out = DateTimeFormatter. ofPattern("yyyy-MM-dd HH:mm:ss").
String input = ...; try { DateTimeFormatter formatter = DateTimeFormatter. ofPattern("MMM d yyyy"); LocalDate date = LocalDate. parse(input, formatter); System. out.
How to convert Instant to ZonedDateTime in Java. In Java, with a given Instant object we can use the ZonedDateTime. ofInstant(Instant instant, ZoneId zone) static method to convert it to a ZonedDateTime object with system time zone as the following example Java code.
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
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);
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With