How to convert OffsetDateTime to Date with time
11,415
That conversion shouldn't work - there is no Date.from
method that takes an OffsetDateTime
directly as far as I see in my IDE and in the docs.
However, passing in an Instant
to Date.from
works fine for me (as in it keeps time information), for example:
val submissionDate: OffsetDateTime = OffsetDateTime.ofInstant(Instant.now(), ZoneOffset.UTC)
val date = Date.from(submissionDate.toInstant())
println(date) // Tue Jul 31 08:26:31 CEST 2018
Related videos on Youtube
Author by
bNd
Updated on June 04, 2022Comments
-
bNd almost 2 years
I have offsetdatetime field and I want to convert into date field. I used
val submissionDate:OffSetDateTime = OffsetDateTime.ofInstant(Instant.now(), ZoneOffset.UTC) val date = Date.from(submissionDate.toInstant())
this conversion returns date without time detail. does I have to manually set time into
date
field like hh:mm::ss or any other inbuilt function there.-
Ole V.V. over 5 yearsIf you do need a
Date
, for example for a legacy API that you don’t want to change just now, why not justDate.from(Instant.now())
or evennew Date()
? If you don’t need aDate
for a legacy API, avoid that class, it is outdated. Stay with the modern API, java.time, exclusively.
-
-
bNd over 5 yearsThanks, yes, you are right. I am passing toInstant only. that is typo mistake. but I tried simple test now, it also works for me. let me check in my project. why is it not working?
-
bNd over 5 yearsI have this date '2018-07-30T18:30Z' in my project. is this creating issue?
-
Ole V.V. over 5 yearsLet me guess, @bNd, you’re in India or Sri Lanka? Then 2018-07-30T18:30Z equals 2018-07-31T00:00 in your local time, which is what
Date.toString
prints, so you will see a time of day of 00:00. This is correct and expected. The time is there, it’s just 00:00.