开发者

Localized date (month and day) and time with NSDate

I want to be able to get the local date and time for wherever my app is 开发者_如何学运维run, based on the iPhone configuration. Specifically I need the date to be of format mm/dd or dd/mm (or dd.mm, mm.dd, dd-mm, mm-dd, etc) depending on the locale, and time is hh:mm. Is this possible with some combination of SDK methods?

Thanks!


I have modified the code so that it just takes the date and time out of the NSDate object with no changes:

NSDate* date = [NSDate date];
NSString* datePart = [NSDateFormatter localizedStringFromDate: date 
                                                    dateStyle: NSDateFormatterShortStyle 
                                                    timeStyle: NSDateFormatterNoStyle];
NSString* timePart = [NSDateFormatter localizedStringFromDate: date 
                                                    dateStyle: NSDateFormatterNoStyle 
                                                    timeStyle: NSDateFormatterShortStyle];
NSLog(@"Month Day: %@", datePart);
NSLog(@"Hours Min: %@", timePart);


Well, I believe the following code works for what I need:

NSString *dateComponents = @"yMMd";
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:[NSLocale currentLocale]];
NSArray *tmpSubstrings = [dateFormat componentsSeparatedByString:@"y"];
NSString *tmpStr;
NSRange r;
if ([[tmpSubstrings objectAtIndex:0] length] == 0) {
    r.location = 1;
    r.length = [[tmpSubstrings objectAtIndex:1] length] - 1;
    tmpStr = [[tmpSubstrings objectAtIndex:1] substringWithRange:r];
} else {
    r.location = 0;
    r.length = [[tmpSubstrings objectAtIndex:0] length] - 1;
    tmpStr = [[tmpSubstrings objectAtIndex:0] substringWithRange:r];
}
NSString *newStr = [[NSString alloc] initWithFormat:@"%@ H:mm", tmpStr];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:newStr];
NSString *formattedDateString = [formatter stringFromDate:[NSDate date]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜