Mitesh Dobareeya Mitesh Dobareeya - 3 months ago 11
Objective-C Question

Unable to get date from string?

I Get

DateTime
string from server "8/27/2016 6:56:23 AM"

And I want to fetch only date from this string.

NSString *StreamStartDateTime=@"8/27/2016 6:56:23 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd"];
NSDate *date1=[dateFormatter dateFromString:StreamStartDateTime];


But the problem is I am getting null in date1.

please help me to find out where I am doing wrong.

Answer

do like

 NSString *StreamStartDateTime=@"8/27/2016 6:56:23 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"]; or use hh:mm:ss a
 NSDate *date1=[dateFormatter dateFromString:StreamStartDateTime];
[dateFormatter setDateFormat:@"yyyyMMdd"];
 NSString *ssecond=[dateFormatter stringFromDate:date1];
  NSDate *finalDate=[dateFormatter dateFromString:ssecond];

final output as

enter image description here