Search code examples
javaswiftdatetimeoffsetlocaldate

Java LocalDateTime/ OffsetDateTime to Swift 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.


Solution

  • 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