我想如果用户从我的字符串设置中选择24小时,他们将获得12小时格式的时间。我正在使用此代码。它没有显示正确的时间。
timePicker.datePickerMode=UIDatePickerModeTime;
[timePicker setDate:[NSDate date]];
[timePicker addTarget:self action:@selector(updateTextFieldd:) forControlEvents:UIControlEventValueChanged];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"h:mm:a"];
theTime = [dateFormat stringFromDate:timePicker.date];
NSLog(@"%@",theTime);
// NSDateFormatter *DateFormatters=[[NSDateFormatter alloc] init];
// [DateFormatters setDateFormat:@"a"];
if (is24h ==YES) {
NSArray *seprates=[theTime componentsSeparatedByString:@":"];
NSString *min = [seprates objectAtIndex:1];
NSLog(@"%@",min);
NSString *hour=[seprates objectAtIndex:0];
int hours=[hour intValue];
NSLog(@"%d",hours);
if (hours==12 &&[min isEqualToString:@"00"]) {
}
else
{
if (hours>=12) {
hours=hours-12;
period=@"PM";
}
else
{
if (hours==12) {
hours=hours-11;
period=@"PM";
}
else if (hours>12)
{
hours=hours-12;
period=@"PM";
}
else
{
period=@"AM";
}
}
}
if (hours ==0) {
theTime=[NSString stringWithFormat:@"00:%@",min];
}
else
{
theTime=[NSString stringWithFormat:@"%d:%@",hours,min];
}
最佳答案
如果要强制使用AM / PM以12小时格式显示日期,请将语言环境设置为en_US。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
NSString *theTime = [dateFormatter stringFromDate: [NSDate date]];
NSLog(@"%@",theTime);
关于ios - 我们如何以12小时格式获取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314115/