当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Converting 12 hour time NSString to 24 hour NSDate object does not work

问题描述:

I need to convert a string for example “12:00 AM” to a date object with 24 hour format of time.

I get NULL whenever i run following code to get date object. Changing locale to en_US_POSIX did not work as well.

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);

If i am doing something wrong please point it out, otherwise guide me about the way i can do it. I have searched a lot, about this kind of string to date conversion but could not find such scenarios.

Any help is appreciated in advance.

网友答案:

Add a letter "a" to your dateFormat. This means, that your time string has "AM" at the end.

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

HH is for 24 hour format where hh is 12 hour am/pm format.

网友答案:

Got it working with following code, Thanks for all others contributors for their help.

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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: