Skip to content

Instantly share code, notes, and snippets.

@ariok
Last active December 29, 2015 18:19
Show Gist options
  • Save ariok/7709718 to your computer and use it in GitHub Desktop.
Save ariok/7709718 to your computer and use it in GitHub Desktop.
Return the integer representation of the required unit for the given date Note: this functions assumes that the current calendar is set to Gregorian and takes as units year, month,day, hour,minute and second.
// Return integer representation of the required unit for the given date
// Note: It assumes that the current calendar is set to Gregorian
+ (NSInteger)unit:(NSCalendarUnit)unit forDate:(NSDate*)date{
// Get the calendar
NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone defaultTimeZone]];
// Get the component
NSDateComponents *componets = [calendar components:unit fromDate:date];
// Not Available in iOS :(
//return [componets valueForComponent:unit];
switch (unit) {
case NSCalendarUnitDay:
return [componets day];
break;
case NSMonthCalendarUnit:
return [componets month];
break;
case NSYearCalendarUnit:
return [componets year];
break;
case NSHourCalendarUnit:
return [componets hour];
break;
case NSMinuteCalendarUnit:
return [componets minute];
break;
case NSSecondCalendarUnit:
return [componets second];
break;
default:
NSLog(@"This Calendar Unit is not supported in the function %s", __FUNCTION__);
return INT_MAX;
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment