2011-05-19 60 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

相关问题