Number of day of current year in iOS

后端 未结 4 550
清歌不尽
清歌不尽 2021-01-16 18:30

I want to find number of day today is in current year. e.g, if today is Mar15, 2012 I should get 75(31 + 29 + 15). Or we can simply say that number of days between today and

4条回答
  •  长发绾君心
    2021-01-16 18:59

    Use the ordinalityOfUnit method of the NSCalendar to get the day number in the year - specify the NSDayCalendarUnit inUnit:NSYearCalendarUnit

    Swift

    let calendar: Calendar = .autoupdatingCurrent
    let dayOfTheYear = calendar.ordinality(of: .day, in: .year, for: Date())
    

    Objective-C

    NSCalendar *currentCalendar = [NSCalendar currentCalendar];
    NSDate *today = [NSDate date];
    NSInteger dc = [currentCalendar  
        ordinalityOfUnit:NSDayCalendarUnit 
        inUnit:NSYearCalendarUnit 
        forDate:today
    ];
    

    gives 269 for Sept 25th 2012

提交回复
热议问题