Search code examples
iosobjective-cdatensdateformatter

Objective-C Convert a string to date and time format


I have an issue of getting a date on converting to NSDate. My requirement is that I have a string like @"01-01-2016 22:22:22" and i want to convert it into date form. Then check the device time format and change its form according to that. Below is my code

NSDateFormatter *dateform=[[NSDateFormatter alloc]init];
[dateform setDateStyle:NSDateFormatterLongStyle];
[dateform setTimeStyle:NSDateFormatterShortStyle];
[dateform setDateFormat:@"MM-dd-YYYY HH:mm:ss"];


NSString *timeStr=@"01-01-2016 22:22:22"; //sample date
NSDate *dt=[dateform dateFromString:timeStr];

NSString *dateString=[dateform stringFromDate:dt];
NSRange *amRange=[dateString rangeOfString:[dateform AMSymbol]];
NSRange *pmRange=[dateString rangeOfString:[dateform PMSymbol]];
BOOL is12h=(amRange.location==NSNotFound && pmRange.location==NSNotFound);
if(is12h)
{
   [dateform setDateFormat:@"MM-dd-YYYY hh:mm:ss"];
}
else
{
   [dateform setDateFormat:@"MM-dd-YYYY HH:mm:ss"];
}
dateString=[dateformatter stringFromDate:dt];

NSDate *dt=[dateform dateFromString:timeStr]; this line converts the string to wrong date.. it gives 20-12-2015 16:52:22 +0000 as the result.. Where am I going wrong please help....


Solution

  • Correct this to yyyy instead of YYYY

    [dateform setDateFormat:@"MM-dd-yyyy HH:mm:ss"];
    

    "YYYY" is week-based calendar year.

    "yyyy" is ordinary calendar year.

    Then, check this format :: "MM-dd-YYYY hh:mm:ss a"

    if(is12h)
    {
        [dateform setDateFormat:@"MM-dd-YYYY hh:mm:ss a"];
    }
    else
    {
        [dateform setDateFormat:@"MM-dd-YYYY HH:mm:ss"];
    }