Unable to parse date from string using NSDateForma

2019-09-08 17:41发布

问题:

I am stuck for a while parsing date in string using NSDateFormatter

Date in string is in below format

1/1/2011 12:00:00 AM

Below is the code I use to parse

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss"];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSDate *date = [[NSDate alloc]init];
date = [dateFormatter dateFromString:@"1/1/2011 12:00:00 AM"];

This code works with date @"12/31/2011" and format @"MM/dd/yyyy"

Please help

回答1:

use my bellow custom method and parse that date into another format...

-(NSString *)changeDateFormat:(NSString*)stringDate dateFormat:(NSString*)dateFormat getwithFormat:(NSString *)getwithFormat{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];

    NSDate *date = [dateFormatter dateFromString:stringDate];

    [dateFormatter setDateFormat:getwithFormat];

    NSString *convertedString = [dateFormatter stringFromDate:date];
    //NSLog(@"Converted String : %@",convertedString);
    return convertedString;
}

use this method like bellow..

 NSString *strSDate = [self changeDateFormat:@"1/1/2011 12:00:00 AM" dateFormat:@"dd/MM/yyyy hh:mm:ss a" getwithFormat:@"dd/MM/yyyy"];
 NSLog(@"Converted String : %@",strSDate);

Set any Format which you want in getwithFormat parameter and set format in dateFormat parameter which you have with your Date string...

OUTPUT IS => Converted String : 01/01/2011



回答2:

Try this

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
//First format date from string
NSDate *date = [dateFormatter dateFromString:@"01/01/2011 12:00:00 AM"];

//Set date formatter to specific format
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];

//Log the value
NSLog(@"%@",[dateFormatter stringFromDate:date]);