简体   繁体   中英

NSDateFormatter returns nil in iOS 8.3

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];

The first part of your code works just fine:

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];

Now stop . date is now an NSDate. That's what you wanted and it's all you need. Throw the date formatter away; you needed it only in order to turn the date string into date. You have finished with it.

Now work purely with NSDate (and NSDateComponents, NSCalendar, etc.) in order to do any desired date math.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM