Gerd Castan Gerd Castan - 5 months ago 31
Swift Question

create DateComponents / NSDateComponents from String and vice versa

Is there an (elegant or preferred) way to convert a DateComponents object to a String and back so that

DateComponents -> String -> DateComponents


is alway possible and the resulting object equals the original object? (not identical) (like
CustomStringRepresentable
)

For
NSDate
/
Date
there is an
NSDateFormatter
/
DateFormatter
that is able to do this trick, converting back and forth.

For
DateComponents
there is a
DateComponentsFormatter
, but it appears to me not to support the direction from
String
to
DateComponents
.

motivation for this question

HealthKit used to store birthdays as
NSDate
up to iOS 9.x.

Starting with iOS 10, HealthKit uses
DateComponents
as a model for birthdays. (And deprecated
NSDate
for birthdays)

I'm trying to reflect HealthKits model change in my own data model of a HealthKit centric app. The most straight forward is to use
DateComponents
in my model as HealthKit does.

As I need to save my model to a file and load it again, the answer to this question would enable me to do this.

The obvious fallback is to convert
DateComponents
to
Date
and save that. But there must be a good reason why Apple deprecated
Date
for birthdays.

Answer

Just save the date components directly via NSKeyedArchiver since NSDateComponents conforms to NS(Secure)Coding.