Arundas Arundas - 2 years ago 170
Objective-C Question

Convert date format in xcode

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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download