i have a string like 2013-03-05T07:37:26.853
and i want to get the Output : 2013-03-05 07:37:26
. I want the final output in NSDate
object. i am using below function to convert desire output. and it returning wrong time.
- (NSDate *) getDateFromCustomString:(NSString *) dateStr
{ NSArray *dateStrParts = [dateStr componentsSeparatedByString:@"T"];
NSString *datePart = [dateStrParts objectAtIndex:0];
NSString *timePart = [dateStrParts objectAtIndex:1];
NSArray *dateParts = [datePart componentsSeparatedByString:@"-"];
NSArray *timeParts = [timePart componentsSeparatedByString:@":"];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:[[timeParts objectAtIndex:0] intValue]];
[components setMinute:[[timeParts objectAtIndex:1] intValue]];
[components setSecond:[[timeParts objectAtIndex:2] intValue]];
[components setYear:[[dateParts objectAtIndex:0] intValue]];
[components setMonth:[[dateParts objectAtIndex:1] intValue]];
[components setDay:[[dateParts objectAtIndex:2] intValue]];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *date = [currentCalendar dateFromComponents:components];
NSLog(@"Date 1:%@",date); // Returns wrong time (2013-03-05 02:07:26)
/* i had tried the below.
NSDateFormatter * format = [[NSDateFormatter alloc] init];
[format setTimeZone:NSTimeZoneNameStyleStandard];
[format setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSLog(@"Date 2:%@",[format stringFromDate:date]); // Returns correct date (2013-03-05 07:37:26)
NSDate *fDate = [format dateFromString:[format stringFromDate:date]];
DLog(@"Date 3:%@",fDate); // Returns wrong time (2013-03-05 02:07:26)
*/
[components release];
return date;
}
Plz suggest me if any idea.