Correct use of NSDateComponents
I've been following the apple docs as well as some code on here and I can't seem to get NSDateComponents to work correctly.
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComp开发者_StackOverflow中文版onents *components = [calendar components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:dateValue];
[calendar release];
dateValue is some date, I only care about the time of it, and the time is 8:00AM. When I check what components is after this, Hour and Minute are both nil.
I also tried inserting this, because I read that you needed to (although not every example has this):
[components setCalendar:calendar];
That code will work. Maybe it's because you're trying to access the hour and minute incorrectly. I did this and got the current hour and minute in the Console window:
NSDate *dateValue = [NSDate date];
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:dateValue];
NSLog(@"hour: %d, minute: %d", [components hour], [components minute]);
[calendar release];
-hour
and -minute
return plain integers, not NSNumber objects.
From ios8 onwards above class constant is deprecated, use below code:
NSDate *dateValue = [NSDate date];
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour|NSCalendarUnitMinute) fromDate:dateValue];
NSLog(@"hour: %ld, minute: %d", (long)[components hour], [components minute]);
精彩评论