In Objective-C, to get the current hours and minutes as integers, do we need to use NSDateComponents and NSCalendar?

I want the current hours and minutes to be whole. So, if it's 3:16 now, I would like to get two integers: 3 and 16.

But it looks like it [NSDate date]will give the number of seconds since 1970, or it can give a string of the current time representation, but there is no easy way to get them as integers?

I see a message to get the current time , but take part in it NSDateComponentsand NSCalendar? It's too complicated ... all it takes is something like

NSDate *date = [NSDate date];
int hour = [date getHour];     // which is not possible

Is there an easier way than using 3 classes NSDate, NSDateComponentsand NSCalendarto get the current hour as an integer or, as a rule, in Objective-C, we usually use the C language localtimeand tmto get the hour as an integer?

+5
source share
3 answers

NSDatejust keeps the time elapsed from a specific key date in order to get more meaningful numbers from this (for example, after daylight saving time, leap years and all the other silly things of the time) you should use NSDateComponentswith the appropriate NSCalendar.

+9
source

1970 , . . , . . " " . :

// Assume you have a 'date'
NSCalendar *gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComps = [gregorianCal components: (NSHourCalendarUnit | NSMinuteCalendarUnit)
                                              fromDate: date];
// Then use it
[dateComps minute];
[dateComps hour];

.

, " ", :

 @interface NSDate (MyGregorianDateComponents)
  - (NSInteger) getGregorianHour;
  - (NSInteger) getGregorianMinute;
  @end
+17

My class can help. https://github.com/TjeerdVurig/Vurig-Calendar/blob/master/Vurig%20Calendar/NSDate%2Bconvenience.m

I'm sure you can figure out the minute part :)

+1
source

All Articles