NSDateFormatter returns nil in iOS 8.3

时间:2015-06-15 15:14:12

标签: ios objective-c iphone

NSString *localTime;
NSString *lUTCTime = @"12-06-2015 14:34:10";

Date i am receiving from server

NSString *dateFormat = @"dd-MM-yyyy HH:mm:ss";
NSTimeZone *inputTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init];
[inputDateFormatter setTimeZone:inputTimeZone];
[inputDateFormatter setDateFormat:dateFormat];
//    NSString *inputString = lUTCTime;
NSDate *date = [inputDateFormatter dateFromString:lUTCTime];//inputString
NSTimeZone *outputTimeZone = [NSTimeZone localTimeZone];
NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
[outputDateFormatter setTimeZone:outputTimeZone];
[outputDateFormatter setDateFormat:dateFormat];
NSString *outputString = [outputDateFormatter stringFromDate:date];//@"12-06-2015 09:46:05"


NSDate *fromDate = [outputDateFormatter dateFromString:outputString];
NSDate *otherDate = [NSDate date];

Here the conversion is getting fail and returning nil.

NSString *temp = [outputDateFormatter stringFromDate:otherDate];
otherDate = [outputDateFormatter dateFromString:temp];

1 个答案:

答案 0 :(得分:2)

代码的第一部分工作正常:

NSString *lUTCTime = @"12-06-2015 14:34:10";
NSString *dateFormat = @"dd-MM-yyyy HH:mm:ss";
NSTimeZone *inputTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init];
[inputDateFormatter setTimeZone:inputTimeZone];
[inputDateFormatter setDateFormat:dateFormat];
NSDate *date = [inputDateFormatter dateFromString:lUTCTime];

现在停止date现在是NSDate。这就是你想要的东西,它就是你所需要的。抛弃日期格式化程序;你需要它才能将日期字符串转换为日期。你已经完成了它。

现在纯粹使用NSDate(和NSDateComponents,NSCalendar等)进行任何所需的日期数学运算。