stringWithFormat的问题

时间:2014-07-23 15:31:16

标签: ios iphone objective-c nsdateformatter nscalendar

请问如何让我的stringWithFormat / initWithFormat显示am / pm而不是24hrs,即使用户从pickerviewer中选择am / pm?当用户选择时间时;例如下午4:15,而不是显示下午4:15作为确认,它显示为16:15。我希望它在下午4:15。请帮助!!

-(IBAction)datePickerValueChanged:(id)sender
{ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"h:mm:ss a"];
NSString *strDate = [dateFormatter stringFromDate:self.pick.date];

dateArray = [strDate componentsSeparatedByString:@":"];

NSDate *current = [NSDate date];
NSString *currentTime = [dateFormatter stringFromDate:current];
NSArray *currArray = [currentTime componentsSeparatedByString:@":"];

curr = [currArray[0] intValue]*60 + [currArray[1] intValue];
min = [currArray[0] intValue]*60 + [currArray[1] intValue] + 30;
next = [[dateArray objectAtIndex:0] intValue]*60 +[[dateArray objectAtIndex:1] intValue];

.... 这是显示值的位置:

             NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
             [dateFormatter setDateFormat:@"yyyy-MM-dd"];
             NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];

             time = [[NSString alloc]initWithFormat:@"%@T%@:%@:00",strDate, [dateArray objectAtIndex:0], [dateArray objectAtIndex:1]];
             NSString *msg = [[NSString alloc] initWithFormat:@"%@ %@ %@ %@ ?", NSLocalizedString(@"do_ticket", nil), self.category.description,NSLocalizedString(@"at", nil),[[NSString alloc]initWithFormat:@"%@:%@", [dateArray objectAtIndex:0], [dateArray objectAtIndex:1]]];
             alert_tick = [[UIAlertView alloc] initWithTitle:nil
                                                     message:msg
                                                    delegate:self
                                           cancelButtonTitle:nil
                                           otherButtonTitles:NSLocalizedString(@"Yes", nil), NSLocalizedString(@"No", nil), nil];
             [alert_tick show];
}

2 个答案:

答案 0 :(得分:0)

使用NSDateFormatter。服务器值以24h格式给出并不重要,因为您的日期格式化字符串可以容纳该值(即,在调用setDateFormat:时代替使用“h”代表am / pm格式,使用“H” “为24小时格式。”

答案 1 :(得分:0)

请改为使用格式@"hh:mm a"

示例:

NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSDate *formattedDate = [formatter stringFromDate:today];
NSLog(@"date : %@", formattedDate);

输出:

date : 09:58 AM