Search code examples
iosobjective-cnsdateformatter

dateFromString returning nil


I have a function to convert NSString to NSDate.

+ (NSDate *)getNSDateFromString:(NSString *)strDate andFormat:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : format];
    NSString *stringTime = strDate;
    NSDate *dateTime = [formatter dateFromString:stringTime];
    return dateTime;
}

The value of strDate is "27-Mar-2018 18:28:09". The format is "dd-MM-yyyy HH:mm:ss"

That function is returning nil value. Can anyone help on this please. Thanks.


Solution

  • Change date format to dd-MMM-yyyy HH:mm:ss

    Here are nice references to understand date format string: Quick Guide to Objective-C DateFormatting & Date_Field_Symbol_Table

    y = year
    Q = quarter
    M = month
    w = week of year
    W = week of month
    d = day of the month
    D = day of year
    E = day of week
    a = period (AM or PM)
    h = hour (1-12)
    H = hour (0-23)
    m = minute
    s = second
    

    If you match this with your date components

    27-Mar-2018 18:28:09 = dd-MMM-yyyy HH:mm:ss
    

    Where

    27   = dd (date day)
    Mar  = MMM (Month)
    2018 = yyyy (year)
    18   = HH (HH - 24 hours format and hh - 12 hours format)
    28   = mm (minutes)
    09   = ss (seconds)