如何格式化用户语言环境的当前日期? [英] How do I format the current date for the user's locale?
问题描述
我在尝试获取当前日期并在当前语言环境中设置其格式的代码.
I have this code where I'm trying to get the current date and format it in the current locale.
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命令构建的NSString.
I know the last line is wrong, but can't seem to figure it out... "insertCmd" is a NSString that I'm building for a FMDB command.
我们将不胜感激,或者提供了指向其中描述了"doc"的指针.
Help would be greatly appreciated, or a pointer to the "doc" where it's described.
推荐答案
在这种情况下,我不会使用 setDateFormat
,因为它将日期格式器限制为特定的日期格式(doh!)-您需要一种动态格式,具体取决于用户的语言环境.
I wouldn't use setDateFormat
in this case, because it restricts the date formatter to a specific date format (doh!) - you want a dynamic format depending on the user's locale.
NSDateFormatter为您提供了一组内置的日期/时间样式,您可以从中进行选择,即NSDateFormatterMediumStyle,NSDateFormatterShortStyle等.
NSDateFormatter provides you with a set of built-in date/time styles that you can choose from, i.e. NSDateFormatterMediumStyle, NSDateFormatterShortStyle and so on.
所以您应该做的是:
NSDate* now = [NSDate date];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
NSString* myString = [df stringFromDate:now];
这将为您提供一个字符串,该字符串具有中等长度的日期和较短的时间,所有这些都取决于用户的语言环境.试用设置,然后选择所需的任何内容.
This will provide you with a string with a medium-length date and a short-length time, all depending on the user's locale. Experiment with the settings and choose whichever you like.
Here's a list of available styles: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/c/tdef/NSDateFormatterStyle
这篇关于如何格式化用户语言环境的当前日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!