2015-10-20 110 views
-1

我需要将字符串例如“12:00 AM”转换为24小时格式的日期对象。 当我运行下面的代码来获取日期对象时,我得到NULL。将语言环境更改为en_US_POSIX也不起作用。将12小时时间NSString转换为24小时NSDate对象不起作用

NSString *TimeIn12hourFormat = @"12:00 am"; 
NSDateFormatter *timeFormatter = [NSDateFormatter new]; 
[timeFormatter setTimeStyle:NSDateFormatterShortStyle]; 
[timeFormatter setDateStyle:NSDateFormatterNoStyle]; 
[timeFormatter setLocale:[NSLocale currentLocale]]; 
[timeFormatter setDateFormat:@"HH:mm"]; 

NSDate *dateIn24HourFormat = [timeFormatter dateFromString:TimeIn12hourFormat]; 
NSLog(@"Time in 24 hour format : %@", dateIn24HourFormat); 

如果我做错了什么,请指出来,否则指导我如何做到这一点。我搜索了很多,关于这种字符串日期转换,但无法找到这种情况。 提前感谢任何帮助。

+0

什么是输出?为什么直接使用'NSLog()'而不是使用日期格式化程序来打印日期对象?你似乎并不了解这里的重要区别。 – trojanfoe

+0

你的'dateFormat'与你的字符串不匹配。 “HH”是24小时,错过了如何阅读“上午”也。 – Larme

+1

如果您稍后设置'DateFormat',Als设置'TimeStyle'和'DateStyle'将不起作用, – rckoenes

回答

1

为您的dateFormat添加字母“a”。这意味着,你的时间字符串最后有“AM”。

[timeFormatter setDateFormat:@"hh:mm a"]; 

HH是24小时格式,其中hh为12小时AM/PM格式。

+0

使用此字母,也会在结果字符串中给出“AM”,这是不期望的。 –

1

得到它与以下代码工作,感谢所有其他贡献者的帮助。

NSString *TimeIn12hourFormat = @"12:00 am"; 
NSDateFormatter *timeFormatter = [NSDateFormatter new]; 
[timeFormatter setDateFormat:@"hh:mm a"]; 
[timeFormatter setTimeStyle:NSDateFormatterShortStyle]; 
[timeFormatter setDateStyle:NSDateFormatterNoStyle]; 
[timeFormatter setLocale:[NSLocale currentLocale]]; 

NSDate *dateIn24HourFormat = [timeFormatter dateFromString:TimeIn12hourFormat]; 
[timeFormatter setDateFormat:@"HH:mm"]; 

TimeIn12hourFormat   = [timeFormatter stringFromDate:dateIn24HourFormat]; 
NSLog(@"Time in 24 hour format : %@", TimeIn12hourFormat); 
相关问题