使用 Swift 添加 days/hours 到 NSDate
Adding days/hours to NSDate with Swift
我知道这是一个非常基本的问题,而且我知道我可能找不到答案,因为我没有问正确的问题,但是如何更改 NSDate 值?
例如,我有一个 date
属性,它设置为 datePicker
的日期,我想创建一个新的 属性,它是前一天date
属性 和一个小时前的另一个。
添加和删除天数
为了避免夏令时出现问题,添加天数时应使用 NSCalendar
Swift 3 :
let tomorrow = Calendar.current.date(byAdding:
.day, // updated this params to add hours
value: 1,
to: now)
Swift 2 :
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
.Day, // updated this params to add hours
value: 1,
toDate: now,
options: .MatchFirst)
Please note that you are NOT mutating the original instance (now
), you are simply building a new one. Infact the NSDate
class is immutable.
我知道这是一个非常基本的问题,而且我知道我可能找不到答案,因为我没有问正确的问题,但是如何更改 NSDate 值?
例如,我有一个 date
属性,它设置为 datePicker
的日期,我想创建一个新的 属性,它是前一天date
属性 和一个小时前的另一个。
添加和删除天数
为了避免夏令时出现问题,添加天数时应使用 NSCalendar
Swift 3 :
let tomorrow = Calendar.current.date(byAdding:
.day, // updated this params to add hours
value: 1,
to: now)
Swift 2 :
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
.Day, // updated this params to add hours
value: 1,
toDate: now,
options: .MatchFirst)
Please note that you are NOT mutating the original instance (
now
), you are simply building a new one. Infact theNSDate
class is immutable.