How to get correct NSDate from NSString without using dateFormatter

because NSDateformatter cannot use a custom calendar, so for a calendar like:

NSCalendar *ISO8601 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
[ISO8601 setMinimumDaysInFirstWeek:7];
[ISO8601 setFirstWeekday:2];


If we need a week

This calendar will translate 2015-04-26 16:00:00 as week 2015-16.

So, I will get the string as 2015-16th week


Then how can I convert the string 2015-16th week

to the correct NSDate or DateComponents, so if you convert this new NSDate or dateComponents, it doesn't lose correctness?


source to share

1 answer

- (NSDate *) dateByAddingWeeks:(NSInteger)dWeeks {

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitTimeZone;
components = [gregorian components:unitFlags fromDate:self]; = + 7 * dWeeks;
return [gregorian dateFromComponents:components];


Not sure. Are you looking for this utility function?



All Articles