0

Possible Duplicate:
Get missing month from timestamp Interval

I am receiving time in terms of seconds from server. Then i am using the below code to convert them into months.

NSDateFormatter * dateFormatter=[[[NSDateFormatter alloc]init]autorelease];
[dateFormatter setDateFormat:@"MMM"];
[dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeStamp]];

The problem is I dont get every month from the server like if I am getting Jan first then second time I'm getting Apr from server but I need to show feb and Mar (missing month) on my iPhone screen (Server people cannot change their code so I have to do it at my end). Can anyone suggest me how can I get missing months.

The same problem is sometimes I get Nov and then Feb from server, but I also have to show Dec and Jan.

Community
  • 1
  • 1
Anshul
  • 279
  • 4
  • 12
  • Could you format this wall of text into a question? Here are some tips you might checkout: http://stackoverflow.com/editing-help – Darin Dimitrov Oct 15 '12 at 12:17
  • NSDateFormatter * dateFormatter=[[[NSDateFormatter alloc]init]autorelease]; [dateFormatter setDateFormat:@"MMM"]; dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeStamp]]; – Anshul Oct 15 '12 at 12:20

1 Answers1

0

As a quick and dirty solution, you could just make an array of all the months, start at the later month, and loop backwards through the month array until you hit the earlier month.

More robust, and even better, is to use NSCalendar and NSDateComponents, like:

NSDateComponents* dateComponents = [[NSDateComponents alloc]init];
[dateComponents setMonth:1];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* newDate = [calendar dateByAddingComponents:dateComponents toDate:originalDate     options:0];
[dateComponents release];

Which would increase / decrease your date by a month.

Matthew Horst
  • 1,991
  • 15
  • 18