I am relatively new to ObjectMapper time string parsing and am facing a huge problem. I have a server sending me time string in "yyyy-MM-dd'T'HH:mm:ss.SSZ" format that I am supposed to parse into my Date object locally. My server is sending me the date in local time zone i.e. GMT+8 so lets say I receive "2018-08-23T15:02:44.000Z" from the server. I need to save this exactly how it is in my realm file. I am using following code for the transformation:
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSZ"
formatter.timeZone = TimeZone.current
recordDateTime <- (map["record_time"], DateFormatterTransform(dateFormatter: formatter))
But the problem is that the date object being saved in realm is 2018-08-23 11:02:44 PM. I believe the DateFormatterTransform accepts the date strings in GMT zone, and thus it is converting it into my local time zone i.e. GMT+8. Is there anyway I can set the time zone for the DateFormatterTransform manually so that I don't get the time shift? We can't change the server at this point in time as the database is quite large and already has every date stored in the local time zone.
Please suggest how to solve this problem. Thanks
Found this to be the quickest solution: Wrote a custom date formatter that would subtract the GMT offset in its date(from: String) method. This is the code snippet:
class MyDateFormatter : DateFormatter {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init() {
super.init()
}
override func date(from string: String) -> Date? {
return super.date(from:string)?.addingTimeInterval(-8*60*60)
}
}