美文网首页兴趣iOS
日历NSCalendar

日历NSCalendar

作者: 沧海的风 | 来源:发表于2016-11-28 17:17 被阅读112次

    日历

    • 某一天
      - (NSInteger)day:(NSDate *)date{
      NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
      return [components day];
      }

    • 某一月
      - (NSInteger)month:(NSDate *)date{
      NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
      return [components month];
      }

    • 某一年
      - (NSInteger)year:(NSDate *)date{
      NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
      return [components year];
      }

    • 某月第一天是周几
      - (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
      NSCalendar *calendar = [NSCalendar currentCalendar];

          [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
          NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
          [comp setDay:1];
          NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
      
          NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
          return firstWeekday - 1;
      }
      
    • 某个月有多少天
      - (NSInteger)totaldaysInMonth:(NSDate *)date {
      NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
      return daysInLastMonth.length;
      }
      [Demo地址](https://github.com/haidumou/Calendar.git

    相关文章

      网友评论

        本文标题:日历NSCalendar

        本文链接:https://www.haomeiwen.com/subject/nkmopttx.html