日期小demo

有個項目需求是作個在日期上選擇的,就是這種:
需求git

網上看了幾個日期的demo都太厚重了,移植起來太麻煩,而後打算本身寫。github

就先寫個簡化的demo看看,主要有幾個關鍵點:api

  • 首先要根據當前日期獲取這個月有幾天
  • 而後判斷這個月份第一天是周幾
  • 再根據上面兩個數據在合理的位置顯示數據
  • 還要記錄下當前的日期方便切換月份
  • 若是調接口的話其實根據後臺給數據比對下對應的日期展現數據便可

其中有一個容易迷糊的是獲取的星期天是第一天,下標是1
因此咱們的數組是這樣的數組

_weekdays = [NSArray arrayWithObjects: [NSNull null],@"星期日", @"週一", @"週二", @"週三", @"週四", @"週五", @"週六", nil];

好吧,看下寫出來的效果:code

demo

總的來講沒什麼難度,就是要熟悉下關於日期的api.component

//3.獲取這個月總天數,填充數據源
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self.currentDate];
    NSUInteger numberOfDaysInMonth = range.length;
    NSLog(@"%lu", (unsigned long)numberOfDaysInMonth);
    
    //4.獲取這個月的第一天爲周幾
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comps = [cal
                               components:NSCalendarUnitYear | NSCalendarUnitMonth
                               fromDate:self.currentDate];
    lastMonthComps.day = 1;
    NSDate *firstDay = [cal dateFromComponents:comps];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *firsComponents = [cal components:calendarUnit fromDate:firstDay];
    
    NSLog(@"%@", [_weekdays objectAtIndex:firsComponents.weekday]);

demo完整代碼blog

相關文章
相關標籤/搜索