如何格式化用户区域设置的当前date?
我有这个代码,我试图获取当前的date,并在当前的区域设置格式。
NSDate *now = [NSDate date]; // gets current date NSString *sNow = [[NSString alloc] initWithFormat:@"%@",now]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"mm-dd-yyyy"]; insertCmd = [insertCmd stringByAppendingString: formatter setDateFormat: @"MM.dd.yyyy"];
我知道最后一行是错误的,但似乎无法弄清楚…“insertCmd”是我为FMDB命令build立的NSString。
帮助将不胜感激,或指向它所描述的“文档”的指针。
在这种情况下,我不会使用setDateFormat
,因为它将date格式化器限制为特定的date格式(doh!) – 您需要一个dynamic格式,具体取决于用户的语言环境。
NSDateFormatter为您提供了一组您可以select的内置date/时间样式 ,即NSDateFormatterMediumStyle,NSDateFormatterShortStyle等等。
所以你应该做的是:
NSDate* now = [NSDate date]; NSDateFormatter* df = [[NSDateFormatter alloc] init]; [df setDateStyle:NSDateFormatterMediumStyle]; [df setTimeStyle:NSDateFormatterShortStyle]; NSString* myString = [df stringFromDate:now];
这将为您提供一个string,具有中等长度的date和短的时间,全部取决于用户的区域设置。 尝试使用设置并select您喜欢的任何一个。
以下是可用样式列表: https : //developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/c/tdef/NSDateFormatterStyle
除了jiayow的回答,您可以指定您的自定义“模板”来获得本地化的版本:
+ (NSString *)formattedDate:(NSDate *)date usingTemplate:(NSString *)template { NSDateFormatter* formatter = [NSDateFormatter new]; formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:template options:0 locale:formatter.locale]; return [formatter stringFromDate:date]; }
US / DE语言环境的示例用法:
NSLocale *enLocale = [NSLocale localeWithLocaleIdentifier:@"en_US"]; NSLocale *deLocale = [NSLocale localeWithLocaleIdentifier:@"de"]; // en_US: MMM dd, yyyy formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"ddMMMyyyy" options:0 locale:enLocale]; // de: dd. MMM yyyy formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"ddMMMyyyy" options:0 locale:deLocale]; // en_US: MM/dd/yyyy formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"ddyyyyMM" options:0 locale:enLocale]; // de: dd.MM.yyyy formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"ddyyyyMM" options:0 locale:deLocale]; // en_US MM/dd formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MMdd" options:0 locale:enLocale]; // de: dd.MM. formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MMdd" options:0 locale:deLocale];
如果你想要本地化的date和时间,这将给你:
NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];
上面的代码不会给你本地化的date和时间。