Skip to content
Advertisement

Kotlin/java – How to convert a date time string to Instant?

I am trying to create an instance of Instant from date and time strings. Date is formatted like this yyyy-MM-dd. So the values could look like this:

JavaScript

I am trying to make a valid instant from this 2 strings like this:

JavaScript

I have also tried with it:

JavaScript

But, that is not working, I get:

JavaScript

Advertisement

Answer

You can combine the date and time strings to create a date-time string in ISO 8601 format which you can parse into LocalDateTime and then convert into Instant by using the applicable ZoneId. Note that the modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.

JavaScript

Output:

JavaScript

ONLINE DEMO

Some alternative approaches:

  1. Create the instance of LocalDateTime can be as suggested by daniu i.e. parse the date and time strings individually and create the instance of LocalDateTime using them.

Demo:

JavaScript

ONLINE DEMO

  1. Create the instance of ZonedDateTime using ZonedDateTime#of(LocalDate, LocalTime, ZoneId) as suggested by Ole V.V.. Another variant that you can try with this approach is by using ZonedDateTime#of(LocalDateTime, ZoneId).

Demo:

JavaScript

ONLINE DEMO

  1. Combine the date and time strings to create a date-time string in ISO 8601 format and parse the same to ZonedDateTime using DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.systemDefault()).

Demo:

JavaScript

ONLINE DEMO

  1. Create an instance of LocalDateTime by parsing the date and time strings, and use the LocalDateTime#toInstant to get the required Instant.

Demo:

JavaScript

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time. Check this answer and this answer to learn how to use java.time API with JDBC.


* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

Advertisement