0

I am struggling with Date and I'm assuming is TimeZone. Currently I get from my backend a string like this "2020-04-07" and when I try to convert it to date it turns into 2020-04-06 22:00:00 +0000. I am in Spain (UTC+2) which I guess this is why it removes 2 hours?

This is my date formatter:

var dateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        dateFormatter.timeZone = TimeZone.current
        return dateFormatter
    }()

And I call it dateFormatter.date(from: startDateString)

I am setting my current timezone but seems to be ignoring it or am I missing something?

I have followed a lot of answers from here but it's always the same result.

Thank you

Joan Cardona
  • 3,463
  • 2
  • 25
  • 43
  • How are you outputting the description of the Date object? If you're just printing it to the console it will show it in UTC by default. – shim Apr 06 '20 at 16:21
  • @shim what?? Really?? I just do a normal print()! How can I see what I'm sending to the server then? – Joan Cardona Apr 06 '20 at 16:24
  • The `Date` object does not have any inherent locale / time zone. It just represents a moment in time. If you want to see that `Date` as a string you have to use a date formatter. Or there's `descriptionWithLocale`. I don't know how you're sending it to your server. – shim Apr 06 '20 at 16:26
  • if I am understanding correctly and if you want ur date unchanged from whats returned from backend, then you can use `TimeZone(secondsFromGMT: 0)` to keep the date unchanged. – AppleCiderGuy Apr 06 '20 at 16:26
  • I see no problem here. 2020-04-06 22:00:00 +0000 is 2020-04-07 00:00:00 in Spain, right? Note that Spain is two hours ahead of UTC, and dates are always `print`ed in UTC. – Sweeper Apr 06 '20 at 16:28
  • 1
    I feel like this question is the one that has been asked hundreds of times before. See [this](https://stackoverflow.com/questions/51397856/why-the-result-of-my-date-object-always-several-hours-behind-the-actual-string-t/51397957#51397957), [this](https://stackoverflow.com/questions/49023814/swift-convert-string-to-date-output-wrong-date/49023964#49023964) and [this](https://stackoverflow.com/questions/55688517/ios-swift-date-without-time/55688630#55688630). Can you explain how your question is different? – Sweeper Apr 06 '20 at 16:35

1 Answers1

2

The Date object does not have any inherent locale / time zone. It just represents a moment in time. If you want to see that Date as a string in a specific locale/time zone you have to use a date formatter. Or there's descriptionWithLocale. If you use print it will print a debug description of the Date instance in UTC.

shim
  • 9,289
  • 12
  • 69
  • 108