Kabali Kabali - 3 months ago 9
iOS Question

Convert date to string with different date format ios?

I search some stack quentions for converting string to date and that's working fine, but i convert my string date to NSDate than it's return me nil. Here is my code :

NSString *dateStr = @"2016-07-29 09:05";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-ddTHH:mm:ss.SSSZ"];
NSDate *date = [dateFormat dateFromString:dateStr];


I want to convert this date to
yyyy-MM-ddTHH:mm:ss.SSSZ
this formate.

What's problem here ?

Answer

do like

NSString *dateStr = @"2016-07-29 09:05";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// set the date format related to what the string already you have
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *date = [dateFormat dateFromString:dateStr];
 [dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
 // again add the date format what the output u need
 [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *finalDate = [dateFormat stringFromDate:date];
NSLog(@"finalDate==%@",finalDate);

output

enter image description here

Comments