Search code examples
iosobjective-cnsdatensdateformatter

Getting incorrect date from 24 hours format time string in Objective C and iOS


I have to fetch date in format (YYYY-MM-dd hh:mm:ss) from a 24 hours format (HH:mm) time string.

I have used the following code but I'm getting wrong output :

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]];
 [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
 [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
 [formatter setDateFormat:@"HH:mm"];

 NSDate *myDate = [formatter dateFromString:@"13:54"];

And I am getting incorrect output : 2000-01-01 13:54:00 +0000

But I want the output like "2017-01-02 13:54:00"

I checked this question but didn't get correct solution.


Solution

  • The output is correct.

    A date string without year / month / day information causes a date 2000/1/1 in NSDateFormatter.

    You need to get the current date and replace the hour and minute components with those of the date string.

    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *todayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    [formatter setDateFormat:@"HH:mm"];
    NSDate *myDate = [formatter dateFromString:@"13:54"];
    NSDateComponents *myDateComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate:myDate];
    todayComponents.minute = myDateComponents.minute;
    todayComponents.hour = myDateComponents.hour;
    NSDate *myCompleteDate = [calendar dateFromComponents:todayComponents];