Search code examples
iosobjective-cnsstringnsdate

How to format a NSDate in dd/MM/YYYY


I'm trying to get an NSDate into the format: 20/05/2014 22:30

here's the code I currently have. [dateFormat setDateFormat:@"YYYY-MM-dd\'T\'HH:mm:ssZZZZZ"]; this works but the format is not like 20/05/2014 22:30 it displays the date in format like: 12-03-2013 12:00:00 +00:00:00

and then when I use:

[dateFormat setDateFormat:@"MM/dd/yyyy"]; I get a null value returned instead of a formatted date.

// timestamp conversion
    NSString *str = [timeStamp objectAtIndex:indexPath.row];
    // convert to date
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  //  [dateFormat setDateFormat:@"YYYY-MM-dd\'T\'HH:mm:ssZZZZZ"];

 [dateFormat setDateFormat:@"MM/dd/yyyy"];

    NSDate *dte = [dateFormat dateFromString:str];
    cell.timeStampLabel.text = [NSString stringWithFormat:@"%@",dte ];

the str original string output before formatting is str 2013-08-23T15:21:19+02:00

thanks for any help


Solution

  • you have to do like this but please first of check your str's date format

    NSString *str = [timeStamp objectAtIndex:indexPath.row];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-MM-dd\'T\'HH:mm:ssZZZZZ"];
    
    
    NSDate *dte = [dateFormat dateFromString:str];
    
    [dateFormat setDateFormat:@"dd/MM/yyyy HH:mm"];
    cell.timeStampLabel.text = [NSString stringWithFormat:@"%@",[dateFormat stringFromDate:dte]];
    

    first time set date format same as in your str.