Format a string into regular time not military
I am trying to format a st开发者_如何学Goring into regular time not military time. How would I do this.
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]];
}
This is the correct way to do it. It will format the time according to the user's locale and preferences — so in Germany or France it will use 24 hour time, and in the US it will use 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]);
If you try to implement date / time formatting yourself, you will only enrage the users that changed their system preferences and those who live in other countries. Do the right thing, use a library function.
NSDateComponents *components = /* ... */;
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease];
NSDate *date = [calendar dateFromComponents: components];
NSString *string = [NSDateFormatter localizedStringFromDate: date dateStyle: NSDateFormatterNoStyle timeStyle: NSDateFormatterShortStyle];
This is a lot simpler and it auto-localizes the result string.
精彩评论