標籤:
SWIFT中如何計算兩個日期間隔多少個小時,其實幾句代碼就可以搞定了,Very Easy,在Playground內輸入以下代碼
var date1 = "2015-06-26 8:15:10"var dateformatter = NSDateFormatter()dateformatter.dateFormat = "yyyy-MM-dd hh:mm:ss"var dateresult = dateformatter.dateFromString(date1)NSDate()var gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)var result = gregorian!.components(NSCalendarUnit.CalendarUnitHour, fromDate: dateresult!, toDate: NSDate(), options: NSCalendarOptions(0))result.hour
附上Playgroud圖片
如果要查看兩個日期間隔多少天又該怎麼做呢?
上面components的第一個參數為Hour那麼應該也有Day吧,轉到定義內看到如下的靜態唯讀屬性,改下這個參數後就可以擷取間隔多少小時了。
static var CalendarUnitEra: NSCalendarUnit { get } static var CalendarUnitYear: NSCalendarUnit { get } static var CalendarUnitMonth: NSCalendarUnit { get } static var CalendarUnitDay: NSCalendarUnit { get } static var CalendarUnitHour: NSCalendarUnit { get } static var CalendarUnitMinute: NSCalendarUnit { get } static var CalendarUnitSecond: NSCalendarUnit { get } static var CalendarUnitWeekday: NSCalendarUnit { get } static var CalendarUnitWeekdayOrdinal: NSCalendarUnit { get }
SWIFT中計算兩個日期間隔多少小時