列出日历年的天数

时间:2013-01-31 16:14:46

标签: iphone ios objective-c nscalendar

我想列出(NSLog)格鲁吉亚日历年(2013年)的所有日期。我已设法使用以下内容获取当前日期:

    NSCalendar*       calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents* components = [calendar components:NSDayCalendarUnit
                                               fromDate:currDate];
    NSInteger  day = [components day];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    NSString *dateString = [dateFormatter stringFromDate:currDate];
    NSLog(@"%@", dateString);

如何打印2013年的所有日期?

2 个答案:

答案 0 :(得分:3)

NSDateFormatter* dateFormatter = [NSDateFormatter new] ;
dateFormatter.dateStyle = NSDateFormatterLongStyle ;

NSDate* today = [NSDate date] ;
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;
NSDateComponents* thisYearComponents = [calendar components:NSYearCalendarUnit fromDate:today] ;
NSDate* firstDateInThisYear = [calendar dateFromComponents:thisYearComponents] ;

NSDateComponents* addDaysComponents = [NSDateComponents new] ;
addDaysComponents.day = 0 ;

while ( TRUE ) {
    NSDate* nextDateInThisYear = [calendar dateByAddingComponents:addDaysComponents toDate:firstDateInThisYear options:0] ;
    NSDateComponents* yearOfNextDateComponents = [calendar components:NSYearCalendarUnit fromDate:nextDateInThisYear] ;
    if ( yearOfNextDateComponents.year == thisYearComponents.year )
        NSLog(@"%@", [dateFormatter stringFromDate:nextDateInThisYear]) ;
    else
        break ;
    addDaysComponents.day += 1 ;
}

WWDC 2011 session 117 - Performing Calendar Calculations是一个很好的信息来源。它涵盖了为什么最好在循环中将n天添加到固定参考日期,而不是重复将1天添加到最近使用的日期。

它还建议使用中午(中午12点)而不是午夜(中午12点)用于您不关心时间的NSDates,因为夏令时导致午夜在某些地方某些日期不存在。但在我的例子中,我并不愿意这样做。

答案 1 :(得分:-1)

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:@"2013-01-01"];


NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [calendar components:kCFCalendarUnitYear fromDate:date];

while ([components year] < 2014) {
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateStyle:NSDateFormatterLongStyle];
    NSString *dateString = [dateFormatter1 stringFromDate:date];
    NSLog(@"%@", dateString);
    date = [NSDate dateWithTimeInterval:60*60*24 sinceDate:date];
    components = [calendar components:kCFCalendarUnitYear fromDate:date];
}