Reputation: 5510
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;
Upvotes: 0
Views: 85
Reputation: 163
this may help you...
NSDictionary *testDict = [[NSDictionary alloc] init];
[testDict setValue:@"14" forKey:@"Day"];
[testDict setValue:@"4" forKey:@"Month"];
[testDict setValue:@"2014" forKey:@"Year"];
NSString *str = [[[NSString stringWithFormat:@"%@-",[testDict objectForKey:@"Day"]] stringByAppendingString:[NSString stringWithFormat:@"%@-",[testDict objectForKey:@"Month"]]] stringByAppendingString:[NSString stringWithFormat:@"%@",[testDict objectForKey:@"Year"]]];
NSDateFormatter * formatter = [NSDateFormatter new];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSDateFormatter *formatter1 = [NSDateFormatter new];
[formatter1 setDateFormat:@"dd-MMM-yyyy"];
NSLog(@"%@",[formatter1 stringFromDate:[formatter dateFromString:str]]);
Upvotes: 0
Reputation: 3656
NSString *str_date = [NSString stringWithFormat:@"%@-%@-%@",[recivedData objectForKey:@"Day"],[recivedData objectForKey:@"Month"],[recivedData objectForKey:@"Year"]];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MM-yyyy"];
NSDate* d = [df dateFromString:str_date];
NSLog(@"%@", d);
[df release];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MMMM-yyyy"];
NSString *stringFromDate = [formatter stringFromDate:d];
NSLog(@"%@",stringFromDate);
[formatter release];
dateResultLabel.text = stringFromDate;
Upvotes: 0
Reputation: 4953
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
Upvotes: 3