1

I want to return a date/time coming from my API. Server is based in Amsterdam.

Swift:

//load from api
print(date)

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
df.timeZone = TimeZone(identifier: "Europe/Amsterdam")
df.locale = Locale(identifier: "en_US")
var updated = dateFormatter.date(from: "\(date)")

//return format
print(updated)

Return:

2020-01-10 00:01:01
Optional(2020-01-09 23:01:01 +0000)

I don't know why, but the output is returning GMT I think. To output should be 2020-01-10 00:01:01 +0000 because Amsterdam is GMT+1.

Bjorn
  • 71
  • 6
  • 5
    Everything is fine. `print` displays dates in UTC. `2020-01-10 00:01:01 +0100` and `2020-01-09 23:01:01 +0000` is the same point in time – vadian Jan 10 '20 at 20:45
  • @vadian The problem is, when I want to store a date (GMT+1) in my realm database, it will be stored as UTC. – Bjorn Jan 10 '20 at 22:58
  • @Bjorn A date is just a point in time. There is no problem to store all dates using UTC/GMT time. When displaying it to the user you just need to parse your date string back to a Date object and use date formatter to display it properly (localized). – Leo Dabus Jan 10 '20 at 23:55
  • Basically you just need to create a timestamp (if you are storing it as a String) https://stackoverflow.com/questions/28016578/how-to-create-a-date-time-stamp-and-format-as-iso-8601-rfc-3339-utc-time-zone/28016692#28016692. or get the date time interval since reference date if you can store it as a Double (preferred) https://stackoverflow.com/a/47502712/2303865. When displaying your date to the user you should respect its locale and the user device settings https://stackoverflow.com/a/28347285/2303865 – Leo Dabus Jan 10 '20 at 23:58
  • Does this answer your question? [Swift - Get local date and time](https://stackoverflow.com/questions/28404154/swift-get-local-date-and-time) – Christophe Jan 11 '20 at 21:04

1 Answers1

0

As vadian explained in the comments it's working as it supposed to.

However, if you want to display a local date instead of UTC, you can use my snippet here.

If know you will always want just one given time zone just modify the code to add the correct amount of seconds. (In the case of Amsterdam time it's +3600 seconds to UTC for example.)

lajosdeme
  • 2,189
  • 1
  • 11
  • 20