我有这个代码,我正在尝试获取当前日期并在当前语言环境中格式化它.
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"];
Run Code Online (Sandbox Code Playgroud)
我知道最后一行是错误的,但似乎无法弄明白......"insertCmd"是我正在为FMDB命令构建的NSString.
非常感谢帮助,或指向描述它的"doc"的指针.
Jia*_*Yow 35
我不会setDateFormat
在这种情况下使用,因为它将日期格式化程序限制为特定的日期格式(doh!) - 您需要一种动态格式,具体取决于用户的语言环境.
NSDateFormatter为您提供了一组可供选择的内置日期/时间样式,即NSDateFormatterMediumStyle,NSDateFormatterShortStyle等.
所以你应该做的是:
NSDate* now = [NSDate date];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
NSString* myString = [df stringFromDate:now];
Run Code Online (Sandbox Code Playgroud)
这将为您提供具有中长日期和短时长度的字符串,所有这些都取决于用户的区域设置.尝试设置并选择您喜欢的任何一个.
以下是可用样式列表: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];
}
Run Code Online (Sandbox Code Playgroud)
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];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20029 次 |
最近记录: |