1

Hello Everybody I want set date in to datepicker from string like above format given in the question I m using following code to set date to datepicker

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];

Is there another way to set it easily?

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 に答える