SwiftDate string parsing returned 1 day less result

172 views Asked by At

I'm trying to parse a date string into a Date class. I'm using SwiftDate for this. But when I tried to parse it, it returned 1 day less than the value in the string. Here are some examples:

let birthString = "1996-10-08"
self.birthday = Date(birthString, format: "yyyy-MM-dd", region: Region.current) 
//Result: self.birthday = 1996-10-07 17:00:00 UTC 

let expiredString = "2019-09-30"
self.membershipExpiredDate = Date(expiredString, format: "yyyy-MM-dd", region: Region.current) 
//Result: self.membershipExpiredDate = 2019-09-29 17:00:00 UTC

How do I fix this error? Thanks.

1

There are 1 answers

0
ielyamani On BEST ANSWER

SwiftDate uses regions, and you are setting the region to Region.current. The date is correct and you can check that using the .timeIntervalSince1970 property. What happens is that when you print the date (which is actually just a TimeInterval, aka Double, a specific point in time, independent of any calendar or time zone), it's printing its description property, with the default time zone UTC (You can see it in your output 17:00:00 UTC).

To print a date using your current locale, use this instance method:

print(date.description(with: Locale.current))