Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 455
gke Avatar asked Oct 31 '25 11:10

gke


1 Answers

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

like image 181
Andreas Oetjen Avatar answered Nov 02 '25 01:11

Andreas Oetjen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!