NSDate的本地化日期(月和日)和时间

时间:2011-03-03 23:46:22

标签: objective-c ios nsdateformatter

我希望能够根据iPhone配置获取运行我的应用程序的本地日期和时间。具体来说,我需要格式为mm / dd或dd / mm(或dd.mm,mm.dd,dd-mm,mm-dd等),具体取决于区域设置,时间为hh:mm。使用SDK方法的某种组合可以实现这一点吗?

谢谢!

2 个答案:

答案 0 :(得分:13)

我修改了代码,以便只需要更改NSDate对象的日期和时间而不做任何更改:

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

答案 1 :(得分:7)

嗯,我相信以下代码可以满足我的需求:

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