NSCalendar--日历、日程、时间(二)

1 获取一个月的天数

func getNumberOfDaysInMonth() -> NSInteger {
    
        let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
        let range = calendar?.rangeOfUnit(.Day, inUnit: .Month, forDate: NSDate())
        return range?.length ?? 0
}

2 获取指定日期的年、月、日、时、分、秒、周几信息

func getDateInfo() {
        
        let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
        let components = calendar?.components([.Year, .Month, .Day, .Hour, .Minute, .Second, .Weekday], fromDate: NSDate())
        
        let year = components?.year
        let month = components?.month
        let day = components?.day
        let hour = components?.hour
        let minute = components?.minute
        let second = components?.second
     let weekDay = components?.weekday

        print("year = \(year)")
        print("month = \(month)")
        print("day = \(day)")
        print("hour = \(hour)")
        print("minute = \(minute)")
        print("second = \(second)")
      print("weekDay = \(weekDay)")  //1表示周日,2表示周一
      
    }

3 计算两个时间之间的天数

func numberOfDaysWithFromDate(date: NSDate, toDate: NSDate) -> NSInteger {
    
        let components = calendar?.components(.Day, fromDate: date, toDate: toDate, options: .WrapComponents)
        
        return components?.day ?? 0
    }

 

posted @ 2016-08-24 10:53  紫洁  阅读(451)  评论(0编辑  收藏  举报