在初始化NSDateFormatter时,需要添加上下面3句:
NSLocale *zh_CNLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
dateFormatter.locale =zh_CNLocale;
dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
swift版
dateFormatter.locale = Locale(identifier: "zh_CN")
dateFormatter.calendar = Calendar(identifier: .iso8601)
例1:日期字符串转Date
+ (NSDate *)dateWithString:(NSString *)dateStr {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLocale *zh_CNLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
dateFormatter.locale =zh_CNLocale;
dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
NSDate *birthdayDate = [dateFormatter dateFromString:dateStr];
return birthdayDate;
}
例2:日期字符串转时间戳
+ (long)timeIntervalFromDataStr:(NSString *)dateStr format:(NSString *)format {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
NSLocale *zh_CNLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
dateFormatter.locale =zh_CNLocale;
dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
NSDate *date = [dateFormatter dateFromString:dateStr];
NSInteger timeInterval = [date timeIntervalSince1970] * 1000;
return timeInterval;
}