Search code examples
iosobjective-cnsstringnsdatensdateformatter

Month changes while convert NSString to NSDate


Here is my code:

NSString *date = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] stringForKey:@"start_date"]];
NSString *time = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] stringForKey:@"start_time"]];  
NSString *dateAndTime = [NSString stringWithFormat:@"%@ %@",date,time];  

Here My date is : 2019-03-14 and my time is : 18:40:00 and dateAndTime is: 2019-03-14 18:40:00

Now when I convert NSString to NSDate it gives different month.
Here is my buggy code :

// convert to date
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    //dateFormat.dateFormat = @"dd MMM YYYY HH:mm:ss";
    [dateFormat setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
    NSDate *dateTime = [dateFormat dateFromString:dateAndTime];
    NSLog(@"dateTime : %@",dateTime);  

Now the o/p is 2019-01-14 13:10:00 +0000
Here time and month both changed.

So What is wrong with my code?

Thanks in advance.


Solution

  • The date format is wrong, just a typo:

    • mm is minute
    • MM is month

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