偶然翻看AliyunOSSSDK源碼的時(shí)候,發(fā)現(xiàn)NSDate+OSS.h中NSDate和NSString相互轉(zhuǎn)換的源碼如下:
NSString * const serverReturnDateFormat = @"EEE, dd MMM yyyy HH:mm:ss z";
+ (NSDate *)oss_dateFromString:(NSString *)string {
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
dateFormatter.dateFormat = serverReturnDateFormat;
return [dateFormatter dateFromString:string];
}
- (NSString *)oss_asStringValue {
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
dateFormatter.dateFormat = serverReturnDateFormat;
return [dateFormatter stringFromDate:self];
不知道大家注意到下面這兩個(gè)設(shè)置
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];// 設(shè)置時(shí)區(qū)
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"]; // 設(shè)置地域
如果沒有這兩個(gè)設(shè)置的話,如果你改一下系統(tǒng)設(shè)置:語言設(shè)置成印度尼西亞文,時(shí)間設(shè)置成12小時(shí)制。那么轉(zhuǎn)換過來的時(shí)間字符串為2019-02-2810.09.14PM夷都, 時(shí)間變成‘.’連接了
要想正確格式化時(shí)間就必須設(shè)置這兩個(gè)屬性像樊。
個(gè)人博客地址:https://youyou0909.github.io