samba
samba

Reputation: 3101

Scala - how to correctly add ZoneOffset when combining LocalDate and LocalTime?

I'm combining LocalDate and LocalTime and need the final result to be in UTC.

Should I add ZoneOffset.UTC to localDate and localTime before combining them or only when creating OffsetDateTime? I've tried different approaches but don't see a difference.

val localDate: LocalDate = java.time.LocalDate.now(ZoneOffset.UTC) // Same as without Offset - 2019-10-30
val localTime: LocalTime = java.time.LocalTime.now(ZoneOffset.UTC) // Same as without Offset - 09:55:25.997

val localDateTimeWithZone: OffsetDateTime = LocalDateTime.of(localDate, localTime)
    .atZone(ZoneOffset.UTC).toOffsetDateTime

Upvotes: 1

Views: 790

Answers (1)

Anonymous
Anonymous

Reputation: 86314

There are many ways to do this.

  • My preferred way is the following. I think it’s simple and pretty free from surprises.
    • OffsetDateTime.of(localDate, localTime, ZoneOffset.UTC)
  • The following options are perfectly fine too.
    • localDate.atTime(localTime).atOffset(ZoneOffset.UTC)
    • localTime.atDate(localDate).atOffset(ZoneOffset.UTC)
    • LocalDateTime.of(localDate, localTime).atOffset(ZoneOffset.UTC)
  • I find the following options more confusing. They work too, but personally I would not use them.
    • localTime.atOffset(ZoneOffset.UTC).atDate(localDate)
    • localDate.atTime(localTime.atOffset(ZoneOffset.UTC))
    • OffsetTime.of(localTime, ZoneOffset.UTC).atDate(localDate)

The list is not exhaustive. All the above give the same result, and also the same result as the code in your question, an OffsetDateTime of your date and time in UTC. So you can make your pick.

Upvotes: 2

Related Questions