2013-05-08 37 views
0

在我的項目我有一個包含這樣轉換在12個小時時間格式的NSString

NSString *[email protected]"20"; 

我想將其轉換爲「08:00」的數據一個NSString。我怎樣才能做到這一點?

我這個嘗試之一:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormatter setDateFormat:@"hh:mm a"]; 
NSString* dateString = [dateFormatter stringFromDate:@"20"]; 

,但我得到這個dateString爲空值。

+1

'stringFromDate'希望你傳遞一個NSDate,但你傳遞一個NSString。 – sosborn 2013-05-08 05:22:03

+0

那麼如何轉換字符串如上 – user2197875 2013-05-08 05:25:00

+0

儘量使用下面的答案。這些答案工作完美。 – 2013-05-08 05:39:20

回答

-1

請儘量使用這一個。我希望它會正常工作......

NSString *[email protected]"20";  
NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"HH"]; 
NSDate *date = [df dateFromString:s]; 

[df setDateFormat:@"hh:mm a"]; 
NSString *newTime = [df stringFromDate:date]; 
NSLog(@"Time : %@",newTime); 
3

您輸入爲NSString,需要輸出NSString

因此,不需要中間工作NSDateNSDateFormatter

您可以通過實現這個:

NSString *[email protected]"20"; 
NSString *time=[NSString stringWithFormat:@"%d:00",[s integerValue]%12]; 
+1

+1。感謝上帝,有人有道理。 – Abizern 2013-05-08 05:40:01

+0

+1真聰明! ;) – HAS 2013-05-08 07:09:09

相關問題