NSDateFormatter格式化时间

获取的时间数据是:"Wed Nov 16 09:55:46 +0800 2016"

- (NSString *)getTimeByCreateDate:(NSString *)create_time {

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];//日期语法

formatter.dateFormat = @"EEE MMM  dd HH:mm:ss zzzz yyyy";

NSDate *weiboDate = [formatter dateFromString:create_time];

//比较微博日期与当前时间的间隔.返回值是一个负数

long long time = ABS([weiboDate timeIntervalSinceNow]);//取绝对值


if (time < 60) {

return [NSString stringWithFormat:@"%lld秒前",time];

}else if (time < 60 * 60){

return [NSString stringWithFormat:@"%lld分钟前",time/60];

}else if (time < 60 * 60 * 24){

return [NSString stringWithFormat:@"%lld小时前",time/(60 * 60)];

}else{

           NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

           formatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];

             formatter.dateFormat = @"MM-dd HH:mm"; 

              //通过dateFormat把日期转成时间字符串

              return [formatter stringFromDate:weiboDate];

}


}




下面是网上的资料

之前的文章,讲到过:[NSDate和NSString相互转换](http://www.superqq.com/blog/2015/06/26/nsdatehe-nsstringxiang-hu-zhuan-huan/)。里面提到过如何讲NSDate转化成NSString。代码如下:

//获取系统当前时间

NSDate*currentDate=[NSDatedate];

//用于格式化NSDate对象

NSDateFormatter*dateFormatter=[[NSDateFormatteralloc]init];

//设置格式:zzz表示时区

[dateFormattersetDateFormat:@"yyyy-MM-ddHH:mm:sszzz"];

//NSDate转NSString

NSString*currentDateString=[dateFormatterstringFromDate:currentDate];

//输出currentDateString

NSLog(@"%@",currentDateString);

运行起来,看看打印的内容:

2015-07-0722:08:57.422TestDemo[6756:1555205]2015-07-0722:08:57

这样写是不是没有什么问题。看着应该是没什么问题,其实问题很大。但是如果你改一下系统设置:语言设置成印度尼西亚文,时间设置成12小时制。

大家应该知道如何去设置吧,不会设置的请不要告诉我你是一名[iOS开发工程师](http://www.superqq.com/blog/2015/06/25/ru-he-cheng-wei-%5B%3F%5D-ming-you-xiu-de-ioskai-fa-gong-cheng-shi/)。再次编译起来,看看打印内容如下:

2015-07-0722:09:14.928TestDemo[6762:1555466]2015-07-0710.09.14PM

是不是愣住了,怎么会这么奇葩,时间怎么是.呢?还有更奇葩的呢,你去设置设置其他语言试试,也许有更多的收获。

如何正确的格式化时间

这也是我们这两天遇到的问题,跟用户几经沟通之后,终于抓到log,发现问题竟然是格式化导致的。怎么解决呢?

这个时候NSLocale的重要性就体现出来了。NSLocale作为大家都不常用的一个类,NSLocale类是将与国家和语言相关的信息进行简单的组合,包括货币、语言、国家等的信息。

所以很简单,我们把dateFormatter的locale属性改一下即可解决这个问题。将下面代码放在dateFormatter初始化之后:

NSLocale*usLocale=[[NSLocalealloc]initWithLocaleIdentifier:@"en_US"];

dateFormatter.locale=usLocale;

看看问题解决没有,编译一下:

2015-07-0722:20:08.411TestDemo[6769:1556968]2015-07-0722:20:08

果然,问题得到完美解决了。

NSLocale用法简介

1. 获取国家、货币、语言地区编码

既然谈到NSLocale,我们就来简单了解一下:

+ISOCountryCodes//所有的ISO定义的国家地区编码

+ISOCurrencyCodes//所有的ISO定义的货币编码

+ISOLanguageCodes//所有ISO定义的语言编码

以上我们可以用NSLog打印出来看一看。

2. 监听用户本地化的设置信息

FOUNDATION_EXPORTNSString*constNSCurrentLocaleDidChangeNotificationNS_AVAILABLE(10_5,2_0);

3. 获取当前系统设置语言的标识符

[[NSLocalecurrentLocale]localeIdentifier];

还有很多关于NSLocale的用法,自己动手多尝试。还有一个小问题。

你可能感兴趣的:(NSDateFormatter格式化时间)