2011-05-19 36 views
0

我想將字符串格式化爲常規時間而不是軍事時間。我將如何做到這一點。將字符串格式化爲常規時間不是軍事

if ([components hour] == 0 && 
     [components minute] == 0 && 
     [components second] == 0){ 

     result.detailTextLabel.text = 
     [NSString stringWithFormat: 
     @"%02ld/%02ld/%02ld - %02ld/%02ld/%02ld All Day", 
     (long)[components month], 
     (long)[components day], 
     (long)[components year], 
     (long)[components1 month], 
     (long)[components1 day], 
     (long)[components1 year]]; 

    } else { 
     result.detailTextLabel.text = 
     [NSString stringWithFormat: 
     @"%02ld/%02ld/%02ld at %02ld:%02ld - %02ld:%02ld", 

     (long)[components month], 
     (long)[components day], 
     (long)[components year], 
     (long)[components hour], 
     (long)[components minute], 
     (long)[components1 hour], 
     (long)[components1 minute]]; 

    } 
+0

你是什麼意思到平時?舉例 – 2011-05-19 00:11:42

+0

1:23 pm 12:20 am 3:23 pm 8:31 am – BDGapps 2011-05-19 00:15:48

回答

2
NSDateComponents *components = /* ... */; 
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease]; 
NSDate *date = [calendar dateFromComponents: components]; 
NSString *string = [NSDateFormatter localizedStringFromDate: date dateStyle: NSDateFormatterNoStyle timeStyle: NSDateFormatterShortStyle]; 

這很簡單,它自動本地化結果字符串。

+0

我如何只是沒有時間的日期? timeStyle:NSDateFormatterShortStyle ??? – BDGapps 2011-05-19 03:13:35

+0

沒錯。 「NSDateFormatterShortStyle」時間爲您提供XX:XX AM/PM和「NSDateFormatterNoStyle」日期不顯示日期。 – 2011-05-19 14:26:17

+0

如何不顯示我只想要日期的時間。 – BDGapps 2011-05-19 14:40:07

4

這是正確的方法。它會根據用戶的語言環境和偏好設置時間格式 - 所以在德國或法國它將使用24小時制,而在美國則使用AM/PM。

NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; 
[fmt setTimeStyle:NSDateFormatterMediumStyle]; // Full time with seconds, no TZ 
[fmt setDateStyle:NSDateFormatterNoStyle]; // No date 
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0]; 
NSLog(@"%@", [fmt stringFromDate:now]); 

如果您嘗試自己執行日期/時間格式化,您只會激活更改其系統首選項和其他國家/地區居住者的用戶。做正確的事情,使用庫函數。

+0

你沒有''釋放'你的'NSDateFormatter'實例。 – 2011-05-19 00:30:37

+0

我假設你知道如何做到這一點。 – 2011-05-19 00:31:41

+0

除了OP沒有根據用戶的喜好要求格式化時間外。他要求一種從24小時轉換到12小時的方法。 – aroth 2011-05-19 00:32:27

相關問題