How to get the name of the months and years between two dates

I would like to get the name of the months and years between two dates. Suppose my start date is 01-23-2010 and the end date is 02-25-2011, so I would like to get a list of months with the corresponding year, for example, January 2010, February 2010 ----- February 2011 .

+4
source share
2 answers

Here's roughly how I did it (warning: type in your browser, yadda yadda):

NSDate *startDate = ...; // your start date NSDate *endDate = ...; // your end date NSDateComponents *monthDifference = [[NSDateComponents alloc] init]; NSMutableArray *dates = [NSMutableArray arrayWithObject:startDate]; NSUInteger monthOffset = 0; NSDate *nextDate = startDate; do { [dates addObject:nextDate]; [monthDifference setMonth:monthOffset++]; NSDate *d = [[NSCalendar currentCalendar] dateByAddingComponents:monthDifference toDate:startDate options:0]; nextDate = d; } while([nextDate compare:endDate] == NSOrderedAscending); 

This should give you an array of NSDate objects representing dates that occur about one month apart, starting from the start date and ending at or near the end date.

If you want to display them in a readable way, you will use NSDateFormatter :

 NSDateFormatter *f = [[NSDateFormatter alloc] init]; [f setDateFormat:@"MMMM yyyy"]; for (NSDate *date in dates) { NSLog(@"%@", [f stringFromDate:date]); } [f release]; 

When I run this on my computer, I get:

 EmptyFoundation[3327:a0f] January 2010 EmptyFoundation[3327:a0f] February 2010 EmptyFoundation[3327:a0f] March 2010 EmptyFoundation[3327:a0f] April 2010 EmptyFoundation[3327:a0f] May 2010 EmptyFoundation[3327:a0f] June 2010 EmptyFoundation[3327:a0f] July 2010 EmptyFoundation[3327:a0f] August 2010 EmptyFoundation[3327:a0f] September 2010 EmptyFoundation[3327:a0f] October 2010 EmptyFoundation[3327:a0f] November 2010 EmptyFoundation[3327:a0f] December 2010 EmptyFoundation[3327:a0f] January 2011 EmptyFoundation[3327:a0f] February 2011 

This may seem rather complicated, but it has several advantages:

  • it will work no matter what calendar system you use. Just change the [NSCalendar currentCalendar] call to another calendar and it will work in that (Hebrew, Islamic, etc.).
  • it counts months with bizarre numbers of days (28 days versus 29 days or calendars with leap months [yes, they exist])
+10
source

What you want to use is NSDateFormatter. The documentation states:

Instances of NSDateFormatter create string representations of NSDate (and NSCalendarDate) and convert text representations of dates and times to NSDate objects. You can express dates and times flexibly using predefined format styles or a custom string format.

If you need to determine which months are actually between two dates, you can use NSCalendar.

+1
source

Source: https://habr.com/ru/post/1342010/


All Articles