4

What's the equivalent of LocalDateTime and OffsetDateTime in Swift 4?

I am trying to encode Java dates and decode them in Swift using Json. It seems like there is only one Date object in Swift.

gke
  • 43
  • 4

2 Answers2

2

Swift uses the Date struct to store a point in time. This is always stored in UTC. If you want the local date time, you either work with Calendar or with DateFormatter, like in this example:

import Foundation

let date = Date();

let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .medium 
dateFormatter.dateStyle = .none // ignore date
dateFormatter.timeZone = TimeZone(secondsFromGMT: 2*60*60)
let localDate = dateFormatter.string(from:date)

print("UTC Time: \(date)")  // 2018-10-18 08:15:07 +0000
print("Local Time: \(localDate)") // 10:15:07 AM

There are multiple ways to convert Date into someting local, just use a search engine of your choice

Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34
  • The `LocalDateTime` class in Java represents a date and a time-of-day without any concept of time zone nor offset-from-UTC. So it does *not* represent a moment, is *not* a point on the timeline. – Basil Bourque Oct 18 '18 at 23:44
  • @BasilBourque I was talking about the Foundation `Date` class, not about any Java classes. `Date` in fact is a point in time. – Andreas Oetjen Oct 19 '18 at 05:49
  • 1
    That’s my point, the title of the Question asks partly about Java `LocalDateTime`. This Answer does not address that part. – Basil Bourque Oct 19 '18 at 06:15
0

Since Java's LocalDateTime is "just a container" for storing local date and time values, I recently copied this idea from Java and created a Swift version: https://github.com/hoereth/LocalDateTime

Mick
  • 954
  • 7
  • 17