Search code examples
iosobjective-cnsstringuilabelnsdateformatter

NSDate to NSString error


I am reciving 3 string values from my server that I put into a NSDictionary. I then pass those value into a NSDateComponent after which I try to create a NSDateFormatter which I am pretty sure is wrong.

The Date formate is supposed to be 01-April-2014 where the data I recive would look like this

{
 Day @"1"
 Month @"4"
 Year @"2014"
}

In the code below you will see I have tried to do this however I am having trouble in two area, the formatting of the NSDateFormatter and secondly how do I pass the date into an NSString so that I can display it in my label.

NSDateComponents *recivedDate = [[NSDateComponents alloc] init];
[recivedDate setDay:[[recivedData objectForKey:@"Day"] intValue]];
[recivedDate setMonth:[[recivedData objectForKey:@"Month"] intValue]];
[recivedDate setYear:[[recivedData objectForKey:@"Year"] intValue]];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-mm-yyy"];

NSString *dateString = [formatter stringFromDate:recivedDate];
dateResultLabel.text = dateString;

Solution

  • you have bifurcated the date components alright, but you did not create an NSDate object from it. Use

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    NSDate *date = [calendar dateFromComponents:recivedDate]; 
    

    and then use ur code to change it to string

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MMM-yyy"];
    
    NSString *dateString = [formatter stringFromDate:date];
    dateResultLabel.text = dateString;
    

    ps: MMM should give you April instead of 04