简体   繁体   中英

SwiftDate string parsing returned 1 day less result

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM