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
Share:
11,415

Related videos on Youtube

bNd
Author by

bNd

Updated on June 04, 2022

Comments

  • bNd
    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.
      Ole V.V. over 5 years
      If you do need a Date, for example for a legacy API that you don’t want to change just now, why not just Date.from(Instant.now()) or even new Date()? If you don’t need a Date for a legacy API, avoid that class, it is outdated. Stay with the modern API, java.time, exclusively.
  • bNd
    bNd over 5 years
    Thanks, 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
    bNd over 5 years
    I have this date '2018-07-30T18:30Z' in my project. is this creating issue?
  • Ole V.V.
    Ole V.V. over 5 years
    Let 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.