Working with NSDate components in Swift

后端 未结 4 462
梦毁少年i
梦毁少年i 2021-02-08 04:19

I have a date that I need to split in some components. for example

let components = NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour
let date = c         


        
4条回答
  •  暖寄归人
    2021-02-08 04:22

    Xcode 8.3.2 • Swift 3.1

    extension Date {
        func xDays(_ x: Int) -> Date {
            return Calendar.current.date(byAdding: .day, value: x, to: self)!
        }
        func xWeeks(_ x: Int) -> Date {
            return Calendar.current.date(byAdding: .weekOfYear, value: x, to: self)!
        }
        var weeksHoursFromToday: DateComponents {
            return Calendar.current.dateComponents( [.weekOfYear, .hour], from: self, to: Date())
        }
        var relativeDateString: String {
            var result = ""
            if let weeks = weeksHoursFromToday.weekOfYear,
                let hours = weeksHoursFromToday.hour,
                weeks > 0 {
                result +=  "\(weeks) week"
                if weeks > 1 { result += "s" }
                if hours > 0 { result += " and " }
            }
            if let hours = weeksHoursFromToday.hour, hours > 0 {
                result +=  "\(hours) hour"
                if hours > 1 { result += "s" }
            }
            return result
        }
    }
    

    let today       = Date()                  // "May 1, 2017, 9:29 PM"
    let yesterday   = Date().xDays(-1)        // "Apr 30, 2017, 9:29 PM"
    let twoWeeksAgo = Date().xWeeks(-2)       // "Apr 17, 2017, 9:29 PM"
    let anotherDate = DateComponents(calendar: .current, year: 2013, month: 12, day: 4).date!  // "Dec 4, 2013, 12:00 AM"
    let anotherDate2 = DateComponents(calendar: .current, year: 2012, month: 12, day: 3).date!  // "Dec 3, 2012, 12:00 AM"
    
    
    yesterday.relativeDateString          // "24 hours"
    twoWeeksAgo.relativeDateString        // "2 weeks"
    anotherDate.relativeDateString        // "177 weeks and 141 hours"
    anotherDate2.relativeDateString       // "230 weeks and 21 hours"
    yesterday.relativeDateString          // "24 hours"
    twoWeeksAgo.relativeDateString        // "2 weeks"
    anotherDate.relativeDateString              // "177 weeks and 141 hours"
    anotherDate2.relativeDateString              // "230 weeks and 21 hours"
    

提交回复
热议问题