在Swift中使用NSDate组件 [英] Working with NSDate components in Swift

查看:86
本文介绍了在Swift中使用NSDate组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期,我需要拆分一些组件。例如

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

let components = NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour
let date = calendar.components(components, fromDate: aDate, toDate: NSDate(), options: nil)
var dateToPrint = "\(date.day) days  \(date.hour) hours"

dateToPrint将是从aDate到现在的天数和小时数。但如果我想要几周而不是几天

dateToPrint will be the number of days and hours from aDate to now. But if i want the number of weeks instead of days

let components = NSCalendarUnit.CalendarUnitWeek | NSCalendarUnit.CalendarUnitHour
let date = calendar.components(components, fromDate: aDate, toDate: NSDate(), options: nil)
var dateToPrint = "\(date.week) weeks \(date.hour) hours"

date.week不存在。那么我怎么解决这个问题?

date.week does not exist. So how I could resolve this?

推荐答案

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"

这篇关于在Swift中使用NSDate组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆