SWIFT中計算兩個日期間隔多少小時

來源:互聯網
上載者:User

標籤:

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中計算兩個日期間隔多少小時

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.