swift 計算兩個日期相差幾天

業務上需要計算兩個日期相差幾天,來顯示上一次操作時間過去多久。官方爲我們提供了NSCalendar類,來管理時間。

天的參數是:NSCalendar.Unit.day

如果計算相差的小時數,可改爲NSCalendar.Unit.hour; day改爲hour。

  // MARK: - 計算兩日期間相差的天數

    /**計算兩日期間相差的天數*/

    class func distancesFrom(_ startingDate: Date, to resultDate: Date) -> Int {


        let gregorian = Calendar(identifier: Calendar.Identifier.gregorian)


        //如果計算相差的小時數,可改爲.CalendarUnitHour; day改爲hour

        let comps = (gregorian as NSCalendar).components(NSCalendar.Unit.day, from: startingDate, to: resultDate, options:.wrapComponents)

        
        return comps.day!

    }

 

整個時間管理類

/**時間日期管理器*/

class HTDateManager {

    

    // MARK: - 日期格式轉字符串

    class func switchToNSDateFrom(_ dateString: String, dateFormat: String) -> Date? {

        let formatter = DateFormatter()

        formatter.dateFormat = dateFormat

        return formatter.date(from: dateString)

    }

     // MARK: - 日期轉字符串格式

    /**日期轉字符串格式*/

    class func switchToStringFrom(_ date: Date, dateFormat: String) -> String? {

         let formatter = DateFormatter()

        formatter.dateFormat = dateFormat

        return formatter.string(from: date)

    }

  // MARK: - 計算兩日期間相差的天數

    /**計算兩日期間相差的天數*/

    class func distancesFrom(_ startingDate: Date, to resultDate: Date) -> Int {

        

        let gregorian = Calendar(identifier: Calendar.Identifier.gregorian)

        

        //如果計算相差的小時數,可改爲.CalendarUnitHour; day改爲hour

        let comps = (gregorian as NSCalendar).components(NSCalendar.Unit.day, from: startingDate, to: resultDate, options:.wrapComponents)

        

        return comps.day!

    }

    // MARK: - 獲取本地時區與世界零時區的時差

    /**獲取本地時區與世界零時區的時差*/

    class func distanceIntervalForLocalTimeZon() -> Int {

         return TimeZone.autoupdatingCurrent.secondsFromGMT(for: Date())

    }

// MARK: - 指定日期,所在的“day”單元,在“month”中有多少個(即指定日期所在月有多少天)

    /**

    指定日期,所在的“day”單元,在“month”中有多少個(即指定日期所在月有多少天)

    */

    class func numberOfDaysInMonthDepandOn(_ date: Date) -> Int {

        return (Calendar.current as NSCalendar).range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: date).length

    }

// MARK: - 指定日期,所在“month“單元裏,該單元的第一個日期(即目標日期所在月的第一天)

    /**

    指定日期,所在“month“單元裏,該單元的第一個日期(即目標日期所在月的第一天)

    */

    class func fetchFirstDayInMonthDepandOn(_ date: Date) -> Date? {

        var startDate: Date?

        var interval: TimeInterval = 0

        startDate = Date()

         Calendar.current.dateInterval(of: .month, start: &startDate!, interval: &interval, for: date)

         return startDate as Date?

    }

// MARK: - 指定日期爲當週的周幾(1爲週日)

    /**

    指定日期爲當週的周幾(1爲週日)

    */

    class func dayIndexInWeeklyDepandOn(_ date: Date) -> Int {

        // 把目標日期轉爲yyy-MM-dd字符串

        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = "yyyy-MM-dd"

        let dateString = dateFormatter.string(from: date)

         // 取出對應的 年、月、日

        var dateArr: [String] = dateString.components(separatedBy: "-")

          // 設置NSDateComponts

        var dateComponts = DateComponents()

       dateComponts.setValue(Int(truncating: NumberFormatter().number(from: dateArr[0])!), for: .year)

        dateComponts.setValue(Int(truncating: NumberFormatter().number(from: dateArr[1])!), for: .month)

        dateComponts.setValue(Int(truncating: NumberFormatter().number(from: dateArr[2])!), for: .day)

        let targetDate = Calendar.current.date(from: dateComponts)!

        let weekdayIndex = (Calendar.current as NSCalendar).component(NSCalendar.Unit.weekday, from: targetDate)

        return weekdayIndex

    }

    

    // MARK: - 指定日期爲周幾

    class func getDayNameBy(stringDate: String) -> String

    {

        let df  = DateFormatter()

        df.dateFormat = "YYYY-MM-dd"

        let date = df.date(from: stringDate)!

        df.dateFormat = "EEEE"

        return df.string(from: date);

    }

    // MARK: - 指定日期所在月一共有多少個周

    /**

    指定日期所在月一共有多少個周

    */

    class func numberOfWeeksInMonthDepandOn(_ date: Date) -> Int {

        // 指定日期當月第一天爲周幾(週日爲1)

        let firstDayIndex = dayIndexInWeeklyDepandOn(fetchFirstDayInMonthDepandOn(date)!)

        // 指定日期所在月有多少天

        let daysInMonth = numberOfDaysInMonthDepandOn(date)

        var weeks: Int = 0

        // 第一週有多少天

        let firstWeekSurplusDays: Int = 7 - firstDayIndex + 1

        weeks += (daysInMonth - firstWeekSurplusDays) / 7 + 1

        weeks += (daysInMonth - firstWeekSurplusDays) % 7 == 0 ? 0 : 1

        return weeks

    }

    // MARK: - 指定日期在所在月爲第幾周

    /**

    指定日期在所在月爲第幾周(第一週爲0)

    */

    class func weekIndexInMonthDepandOn(_ date: Date) -> Int {

        // 指定日期當月第一天爲周幾(週日爲1)

        let firstDayIndex = dayIndexInWeeklyDepandOn(fetchFirstDayInMonthDepandOn(date)!)

        // 第一週擁有的天數

        let daysInFirstWeek = 7 - firstDayIndex + 1

        // 指定日期爲當月的幾號

        let dateString = LWDateManager.switchToStringFrom(date, dateFormat: "yyyy-MM-dd")

        let dateComposes = dateString?.components(separatedBy: "-")

        let days = NumberFormatter().number(from: dateComposes!.last!)!.intValue

        var weeks: Int = 0

        if days <= daysInFirstWeek {

            weeks += 0

        } else {

            weeks += (days - daysInFirstWeek) / 7

            if (days - daysInFirstWeek) % 7 > 0 {

                weeks += 1

            }

        }

        return weeks

    }

    /**

     * 返回day天后的日期(若day爲負數,則爲|day|天前的日期)

     */

    class func dateGenerateNewDate(_ date:NSDate,_ day:NSInteger) -> NSDate {

        let calendar = NSCalendar.current

        let componentsToAdd = NSDateComponents()

        componentsToAdd.day = day

        let dateAfterDay = calendar.date(byAdding: componentsToAdd as DateComponents, to: date as Date, wrappingComponents: false)

        return dateAfterDay! as NSDate

    }

    //返回當前天的字符串

    class func currentDayString()->String{

        let dateformatter = DateFormatter()

        dateformatter.dateFormat = "yyyy-MM-dd"

        let date = Date()

        return dateformatter.string(from: date)

    }

    //返回月份的英文簡寫

    class func monthString(_ Index: Int)->String{

        switch Index {

        case 1: return "Jan"

        case 2: return "Feb"

        case 3: return "Mar"

        case 4: return "Apr"

        case 5: return "May"

        case 6: return "Jun"

        case 7: return "Jul"

        case 8: return "Aug"

        case 9: return "Sep"

        case 10: return "Oct"

        case 11: return "Nov"

        case 12: return "Dec"

        default:return ""

        }

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章