首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在xcode中统计时间差中的Leap年天数

在xcode中统计时间差中的Leap年天数
EN

Stack Overflow用户
提问于 2012-05-17 02:44:18
回答 3查看 1.2K关注 0票数 1

我正在尝试为一个可以追溯到19世纪的应用程序确定两个不同日期之间的闰年天数-这是一个方法示例:

代码语言:javascript
运行
复制
-(NSInteger)leapYearDaysWithinEraFromDate:(NSDate *) startingDate toDate:(NSDate *) endingDate {

// this is for testing - it will be changed to a datepicker object
NSDateComponents *startDateComp = [[NSDateComponents alloc] init];
[startDateComp setSecond:1];
[startDateComp setMinute:0];
[startDateComp setHour:1];
[startDateComp setDay:14];
[startDateComp setMonth:4];
[startDateComp setYear:2005];

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

//startDate declared in .h//
startDate = [GregorianCal dateFromComponents:startDateComp];
NSLog(@"This program's start date is %@", startDate);


NSDate *today = [NSDate date];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *temporalDays = [GregorianCal components:unitFlags fromDate:startDate toDate:today options:0];

NSInteger days = [temporalDays day];

// then i will need code for the number of leap year Days

return 0;//will return the number of 2/29 days

}

所以我有两个日期之间的总天数。现在我需要减去闰年天数?

PS -我知道在这个例子中有两个闰年,但这个应用程序将追溯到19世纪……

EN

Stack Overflow用户

发布于 2015-06-08 15:57:15

对于Swift

代码语言:javascript
运行
复制
func getLeapCount(startDate : NSDate , endDate : NSDate)-> Int{
    var intialDate = startDate
    var dateComponent = NSDateComponents()
    dateComponent.day = 1
    var leapCount = 0;
    var currentCalendar = NSCalendar.currentCalendar()
        while (intialDate.compare(endDate) == NSComparisonResult.OrderedAscending) {
            intialDate = currentCalendar.dateByAddingComponents(dateComponent, toDate: intialDate, options: NSCalendarOptions.allZeros)!            
            if self.isLeapYear(startDate){
                ++leapCount
            }
    }

    return leapCount
}
func isLeapYear (year : NSDate )-> Bool{
    let cal = NSCalendar.currentCalendar()
    let year = cal.component(NSCalendarUnit.CalendarUnitYear, fromDate: year)
    return (( year%100 != 0) && (year%4 == 0)) || year%400 == 0;
}
票数 3
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10624696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档