Convert date format in returns wrong date xcode [d

2019-03-01 09:29发布

问题:

This question already has an answer here:

  • NSDateFormatter show wrong year 1 answer

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.

回答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);