Reputation: 250
My situation is as follows: I get a ticket info from an API Call, and I can see in my Realm Browser, that the dates of when I activated the ticket and when it expires are saved correctly in the database in UTC.
In the Database, using Realm Browser, I can see that startTime is Apr 25, 2017, 1:45:30 PM and endTime is Apr 26, 2017, 6:45:30 AM. (My local time was 9:45:30 AM at the time of activating my ticket - so this is correctly setup on servers end)
However, when I access that date later on in code and retrieve it from database it gives me a date with an offset!!! (And no, it's not a date in local timezone - it should've been a date saved in UTC).
Here's some code I use to get the info from database and display it:
func getTickets() -> [Ticket] {
let tickets = userInfo?.tickets.filter("state == %@", "activated").map({ (dbTicket) -> Ticket in
var startTime: Date? = nil
var endTime: Date? = nil
if let start = dbTicket.startTime, let end = dbTicket.endTime {
print("START ", dbTicket.startTime,
"\nNOW ", NSDate(),
"\nEND ", dbTicket.endTime)
startTime = start as Date
endTime = end as Date
}
print("START ", dbTicket.startTime,
"\nNOW ", Date(),
"\nEND ", dbTicket.endTime)
return Ticket(id: dbTicket.id, startTime: startTime, endTime: endTime)
}) ?? []
return tickets
}
And here's what gets printed in the console:
START Optional(2017-04-25 17:45:30 +0000)
NOW 2017-04-25 13:46:15 +0000
END Optional(2017-04-26 10:45:30 +0000)
START Optional(2017-04-25 17:45:30 +0000)
NOW 2017-04-25 13:46:15 +0000
END Optional(2017-04-26 10:45:30 +0000)
Which is incorrect! START should be almost the same as NOW. So why START and END dates are read from Realm database incorrectly ? Especially that I can see then in the Realm Browser and there they are saved correctly.
Upvotes: 0
Views: 89
Reputation: 18308
NSDate
represents a specific point in time, independent of any time zone. The only time that a time zone is associated with an NSDate
is when creating a string representation of it (in your case, this happens when print
ends up calling -[NSDate description]
). If you want to control which time zone the date is formatted with you can explicitly convert NSDate
to the string using NSDateFormatter
, which allow you to control the time zone that's used.
Upvotes: 1