2011-10-29 52 views
7

我有一个NSDate对象,我从中创建两个NSStrings:日期和时间。目前我将日期格式设置为20111031,时间格式为23:15。格式化设备当前区域设置后的日期和时间

我想要做的是将其格式化为设备(iPhone,iPad,iPod Touch)当前的区域设置(不是语言!)。因此,例如:

  • 设置区域的设备,美国会显示(从我的头顶)11年10月31日和时间下午11:15
  • 的设备设置区域荷兰将显示:31- 10-2011和时间23.15
  • 的设备设置为区域瑞典会显示:2001-10-31时间23:15

我怎样才能做到这一点?

+1

格式。 –

回答

37

下应该是足够的,因为一个NSDateFormatter默认拥有手机的默认语言环境:

NSDate *date = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
[dateFormatter setDateStyle:NSDateFormatterShortStyle]; 
NSLog(@"%@",[dateFormatter stringFromDate:date]); 

FYI这里与美国发生了什么,荷兰和瑞典:

[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; 
NSLog(@"%@",[dateFormatter stringFromDate:date]); 
// displays 10/30/11 7:09 PM 
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"nl_NL"]]; 
NSLog(@"%@",[dateFormatter stringFromDate:date]); 
// displays 30-10-11 19:09 
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"]]; 
NSLog(@"%@",[dateFormatter stringFromDate:date]); 
// displays 2011-10-30 19:09 
+0

非常感谢。不知道。 (虽然现在感觉有点愚蠢);) –

+2

我的荣幸!我只知道这一点,因为我过去三天花了很多时间来处理与NSDate有关的错误,并且学习了更多关于这个东西的方法,这比我所希望的要多:P – yuji

7

许多伟大的代码片段在这里。有人甚至在我的脑海里更好地为国际日期格式(当所有我要的是日期,而不是时间)这是手机知悉设置区域设置语言:使用手机的默认语言环境

NSDate *date = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]]; 
[dateFormatter setTimeStyle:NO]; 
[dateFormatter setDateStyle:NSDateFormatterShortStyle]; 
NSLog(@"%@",[dateFormatter stringFromDate:date]); 
相关问题