简体   繁体   中英

iPhone - adjusting the date on a UIDatePicker

I have the hour and the minute as NSIntegers (I don't care about the seconds... it may be 00) and I have a UIDatePicker adjusted to display just time (UIDatePickerModeTime).

Simple question: how do I set an hour on the UIDatePicker? Hours are in the 24h format (as it comes from the picker naturally).

Suppose this:

NSInteger hour = 17;
NSInteger minute = 12;
[myTimePicker setDate: ????];

I know I have to convert that hour and minute to NSDate, but how do I do that without including a day? I just need time.

I have read this example , but it also considers the day.

How do I construct a NSDate of just time, so I can adjust my UIDatePicker?

thanks

You should be able to do this,

NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setHour:17];
[dateComponents setMinute:12];

myTimePicker.date = [gregorian dateFromComponents:dateComponents];

You can later get the hour and minute like this,

NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [gregorian components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:myTimePicker.date];

int hour = [dateComponents hour];
int minute = [dateComponents minute];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM