views:

506

answers:

2

Hi in my application i need to get the hour and minute seperately,

NSString *currentHour=[string1 substringWithRange: NSMakeRange(0,2)]; int currentHourInNumber=[currentHour intValue];

consider string1 contains "11:59:13 AM" which is coming from datepicker.

here if i use above code, its okay to get hour if its greaterthan 9. else i need to change NSMakeRange(0,1) to get hour betwee 1 to 9.

is there any methods to get the hour, minutes ..

Thanks in advance.. please provide me sample code

+1  A: 

NSDateComponents, All you need can be found here: http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/DatesAndTimes/Articles/dtCalendars.html

Paul Lynch
+1  A: 

Use an NSDateFormatter to convert string1 into an NSDate, then get the required NSDateComponents:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"<your date format goes here"];
NSDate *date = [dateFormatter dateFromString:string1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(kCFCalendarUnitHour | kCFCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

I haven't tested it - just typed this into the browser.

Thomas Müller
thanks Thomas this is what exactly im looking for
mac
Hi One more doubt, is it possible to change the hour, minute in NSDate
mac
To change the hour and minute, maybe look into NSDate's + dateWithTimeIntervalSinceReferenceDate:. That method lets you add a specific amount of seconds to date (and return a new date).
Thomas Müller