1

I want to convert date from 23 May, 2017 to 23-05-2017.

I have tried with the following code but it returns 25-12-2016.

NSDateFormatter *oldFormatter = [NSDateFormatter new];
[oldFormatter setDateFormat:@"dd MMM, YYYY"];
NSDate *oldDate = [oldFormatter dateFromString:dateStr];

NSDateFormatter *newFormatter = [NSDateFormatter new];
[newFormatter setDateFormat:@"dd-MM-YYYY"];

I am using Xcode 8.2.1. Thank You.

user6788419
  • 7,196
  • 1
  • 16
  • 28
  • 4
    "yyyy" instead of "YYYY". See this: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns to find why. – Larme Jul 27 '17 at 10:09

1 Answers1

1

You need to do below changes:

YYYY --> yyyy

Updated Code:

    NSString *strInputDateString = @"23 May, 2017";
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd MMM, yyyy"];

    //Set new dateFormate
//    23-05-2017
    NSDate *date1 = [dateFormat dateFromString:strInputDateString];
    [dateFormat setDateFormat:@"dd-MM-yyyy"];

    NSString *strOutputDateString = [dateFormat stringFromDate:date1];
    NSLog(@"%@",strInputDateString);
    NSLog(@"%@",strOutputDateString);
Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56