Number of day of current year in iOS

后端 未结 4 520
清歌不尽
清歌不尽 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 19:04

    Using the NSDate, NSDateComponents and NSCalendar classes, you can quite easily calculate the amount of days between the last day of the previous year and today (which is the same as calculating today's number in the current year):

    // create your NSDate and NSCalendar objects
    NSDate *today = [NSDate date];
    NSDate *referenceDate;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // get today's date components
    NSDateComponents *components = [calendar components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:today];
    
    // changing the date components to the 31nd of December of last year
    components.day = 31;
    components.month = 12;
    components.year--;
    
    // store these components in your date object
    referenceDate = [calendar dateFromComponents:components];
    
    // get the number of days from that date until today
    components = [calendar components:NSDayCalendarUnit fromDate:referenceDate toDate:[NSDate date] options:0];
    NSInteger days = components.day;
    

提交回复
热议问题