1

大家好,我想从问题中给出的上述格式的字符串中将日期设置为日期选择器,我使用以下代码将日期设置为日期选择器

NSString *tmStr=[selectedDics objectForKey:@"Time"];
NSArray *timeStr=[tmStr componentsSeparatedByString:@" "];
NSString *fStr=[timeStr objectAtIndex:1];
NSArray *Time=[[timeStr objectAtIndex:0]componentsSeparatedByString:@":"];
NSInteger hour=[[Time objectAtIndex:0] intValue];

NSString *str=[NSString stringWithFormat:@"%i:%i",hour,[[Time objectAtIndex:1]intValue]];

NSString *a;
if ([fStr isEqualToString:@"PM"]) 
{
    a=@"PM";
    hour=hour+12;
}else
{
    a=@"AM";
    if (hour==12) {
        hour=0;
    }
}
NSCalendar *calender = [NSCalendar currentCalendar];
[calender setTimeZone:[NSTimeZone defaultTimeZone]];
unsigned currentFlag = NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *comps = [calender components:currentFlag fromDate:[NSDate date]];
comps.hour = hour;
comps.minute = [[Time objectAtIndex:1]intValue];
datePicker.date = [calender dateFromComponents:comps];

还有其他方法可以轻松设置吗?

4

1 回答 1

3
 NSDateFormatter *formatter;
 formatter = [[NSDateFormatter alloc] init];
 [formatter setDateFormat:@"h:mm a"];

 NSDate *date=[formatter dateFromString:@"12:30 AM"]; 
 [datepicker setDate:date];
于 2012-07-20T12:23:27.457 回答