開源了一個優(yōu)化NSDate各種處理邏輯的組件,用Swift2.0 寫的炉抒。GitHub地址奢讨。
讓NSDate使用起來爽很多。下面是介紹
DateSuger
DateSuger 是一個優(yōu)化Cocoa時間焰薄、日期使用方式的組件拿诸。Cocoa的 NSDate、NSDateComponent塞茅,NSCalendar等類提供了極其強大的日期處理的功能亩码,但是使用起來卻十分繁瑣。DateSuger就是基于Swift2.0語言的對日期處理邏輯的一系列的語法糖野瘦。
要求
- iOS8 +
- Swift 2.0 +
安裝
Cocoapods
pod 'DateSuger'
手動
直接將Source目錄下的swift文件導入到工程描沟。
使用
日期編輯
我們想獲得當前時間十天后的NSDate對象飒泻,在Cocoa中是這么做的:
let date1 = NSDate()
let components = NSDateComponents()
components.day = 10
let calenar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let date2 = calenar?.dateByAddingComponents(components, toDate: date1, options: [])
在DateSuger里面一句話就可以代替:
let date3 = NSDate().dateByAddingDays(10)
還想更簡單嗎?還能這樣:
let date4 = NSDate() + .Day(10)
這樣相比于傳統(tǒng)的Cocoa的接口吏廉,更加易用和容易理解泞遗。計算1年零3個月之后:
let date5 = NSDate() + .Year(1) + .Month(3)
就是這么簡單~
日期信息
如果我們要知道今天是幾月,或是星期幾席覆,傳統(tǒng)代碼如下:
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let components = calendar?.components([.Weekday,.Month], fromDate: NSDate())
let weekday = components?.weekday
let month = components?.month
通過DateSuger可以直接從NSDate實例中獲取:
let weekday = NSDate().weekday
支持的日期信息有:
Era
Year
Month
Day
Hour
Minute
Second
Quarter
Weekday
WeekdayOridinal
WeekOfMonth
WeekOfYear
DayOfYear
其他信息判斷
DateSuger支持對一些常用信息的判斷史辙,通過實例代碼展示:
let v1 = NSDate().isInLeapYear // 判斷是否是閏年
let v2 = NSDate().isToday // 判斷是否是今天
let v3 = NSDate().isTomorrow // 判斷是否是明天
let v4 = NSDate().isYesterday // 判斷是否是昨天
let v5 = NSDate().isSameDay(someDate) // 判斷是否和某日期在同一天
快速創(chuàng)建NSDate
能夠通過指定年月日、小時佩伤、分鐘聊倔、秒來創(chuàng)建NSDate
let date1 = NSDate.dateWithYear(2015, month: 3, day:
let date2 = NSDate.dateWithYear(2015, month: 3, day: 28, hour: 3, minute: 12, second: 12)
日期比較
能夠直接通過操作符來比較NSDate,這樣是不是方便了很多
if date1 > date2 {
//...
}
if date1 >= date2 {
//...
}
if date1 == date2 {
//...
}