ios - 我们如何以12小时格式获取日期

标签 ios objective-c iphone

我想如果用户从我的字符串设置中选择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/

相关文章:

ios - TWRequest 是否适用于 twitter streaming api?

objective-c - XIB 无法在静态库中找到类

objective-c - OSX SDK 上的文件管理器类?

ios - 如何通过Objective C连接到SQL Server

ios - 在保持用户位置居中的同时在 MKMapView 上安装注释

ios - 如何获得相机Objective-C的分辨率?

ios - 隐藏 UIStackview 的 subview 时自动布局冲突

读取字符串值时 iPhone 泄漏

ios - 如何向 GET 请求添加 header 字段和参数?

iphone - 秒与分钟的换算