2015-10-20 85 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); 
相關問題