将字符串格式化为常规时间而非军事

时间:2011-05-19 00:09:50

标签: iphone objective-c ios4 ipad

我正在尝试将字符串格式化为常规时间而不是军事时间。我该怎么做呢。

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

    }

2 个答案:

答案 0 :(得分: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]);

如果您尝试自己实施日期/时间格式,则只会激怒更改其系统偏好的用户和居住在其他国家/地区的用户。做正确的事,使用库函数。

答案 1 :(得分:2)

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

这样更简单,它会自动本地化结果字符串。