Search code examples
iosnsdatensdateformatternsdatepicker

Convert NSDate to NString issue


Hi I m pick the date from UIDatePicker and convert it in NSstring.. All the date working fine. Hi have set maximum date as 2001-12-31. When i choose this date the string return as "2002-12-31"

dOBPicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(20, 30, 360, 55)];
dOBPicker.datePickerMode = UIDatePickerModeDate;


NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYY-MM-dd";
dOBPicker.maximumDate = [formatter dateFromString:@"2001-12-31"];

Conversion here

NSDateFormatter *dateOfBirthFormat =[[NSDateFormatter alloc]init];
dateOfBirthFormat.dateFormat = @"YYYY-MM-dd";

[dateOfBirthFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSString *dob = [dateOfBirthFormat stringFromDate:dOBPicker.date];

NSLog(@"The dob is %@", dob);

Output as : 2002-12-31


Solution

  • You need to use "yyyy" not "YYYY".

    "Y": Year (in "Week of Year" based calendars). Normally the length specifies the padding, but for two letters it also specifies the maximum length. This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.

    Y   year of "Week of Year":  
        Y -> 1997
    

    "y": Year. Normally the length specifies the padding, but for two letters it also specifies the maximum length.

    y   year:   
        yy -> 96  
        y or yyyy -> 1996
    

    See: ICU Formatting Dates and Times
    Also: CLDR Date Field SymbolTable.