hacker hacker - 5 months ago 12
iOS Question

date formatter giving wrong dates in iOS?

I had an application in which i am using a date formatter for a string like
"

6/30/2016 1:00:00 PM
" like this
30-Jun-2016 1:00
.I am doing like this

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"mm/dd/yyyy hh:mm:ss a"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat setDateFormat:@"dd-MMM-yyyy hh:mm"];
NSString *stringDate = [dateFormat stringFromDate:date];
return stringDate;


but it is not giving me wrong date like this 30-Jan-2016 1:00 .

can anybody point me where i am going wrong ?

Answer

You have given the wrong date format you need to capitalize month MM not small, small mm is for minute. Change your code like this.

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat setDateFormat:@"dd-MMM-yyyy hh:mm"];
NSString *stringDate = [dateFormat stringFromDate:date];
return stringDate;

Hope this will help you.

Comments