问题
Please how do I make my stringWithFormat/initWithFormat to display am/pm instead of 24hrs, even though users selects am/pm from the pickerviewer? When a user select time; eg 4:15 pm, instead of it to display 4:15pm as confirmation, it displays 16:15 instead. I want it as 4:15pm. PLEASE HELP!!
-(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];
....This is where values are displayed:
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];
}
回答1:
Use NSDateFormatter
. It doesn't matter that server values are given in 24h format, because your date formatting string can accommodate that (i.e. instead of using "h" for hours when calling setDateFormat:
, which represents am/pm format, use "H" for 24h format).
回答2:
Use the format @"hh:mm a"
instead.
Example:
NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSDate *formattedDate = [formatter stringFromDate:today];
NSLog(@"date : %@", formattedDate);
Output:
date : 09:58 AM
来源:https://stackoverflow.com/questions/24914761/issues-with-stringwithformat