我们如何以12小时格式获取日期 [英] How we get date in 12 hour format
本文介绍了我们如何以12小时格式获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望如果用户从我的字符串设置中选择24小时,他们将获得12小时格式的时间。我正在使用此代码。它没有显示正确的时间。
I want if user select 24 hour from setting on my string they get time in 12 hour format. I am using this code. It does not show the proper time.
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。
If you want to force the date to be displayed in 12 hour format with AM/PM, set the locale to 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);
这篇关于我们如何以12小时格式获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文