1

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
    Possible duplicate of [Converting string to date returning the day before](https://stackoverflow.com/questions/42786812/converting-string-to-date-returning-the-day-before) – Rakesha Shastri Oct 06 '18 at 05:54
  • Your code works just fine. – rmaddy Oct 06 '18 at 05:58
  • @rmaddy Ah yeah it does. Even though the value in the debugger said it was the day before, but when I printed it it is correct. Okay, I get it now. I think it's like what the page that Rakesha Shastri said, it's because of the timezone difference. Thanks. – Bawenang Rukmoko Pardian Putra Oct 06 '18 at 06:30

1 Answers1

1

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))
ielyamani
  • 17,807
  • 10
  • 55
  • 90