我想取两个日期之间的月份和年份的名称。假设我的开始日期是2010年1月23日,结束日期是2011年2月25日,因此我希望获得相关年份的月份列表,例如2010年1月,2010年2月-2011年2月。
发布于 2011-03-03 00:21:43
我大概是这样做的(警告:在浏览器中输入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);这将为您提供一个NSDate对象数组,这些对象表示大约相隔一个月的日期,从开始日期开始,到结束日期或结束日期左右结束。
如果您希望以可读的方式显示它们,则可以使用NSDateFormatter
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"MMMM yyyy"];
for (NSDate *date in dates) {
NSLog(@"%@", [f stringFromDate:date]);
}
[f release];当我在我的计算机上运行它时,我得到:
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这可能看起来有点复杂,但它有几个优点:
[NSCalendar currentCalendar]调用更改为不同的日历,它将在该日历(希伯来语、伊斯兰教等)中工作。发布于 2011-03-03 00:19:58
您想要使用的是NSDateFormatter。文档中写道:
NSDateFormatter的
实例创建NSDate (和NSCalendarDate)对象的字符串表示形式,并将日期和时间的文本表示形式转换为NSDate对象。您可以使用预设的格式样式或自定义格式字符串灵活地表示日期和时间。
如果需要确定两个日期之间的实际月份,可以使用NSCalendar。
https://stackoverflow.com/questions/5169751
复制相似问题