date(byAdding :)在Swift 4

时间:2017-11-04 16:52:31

标签: ios swift nsdate swift4

我有以下代码:

let defaults = UserDefaults.standard
if let dateOpened: Date = defaults.object(forKey: "lastOpened") as? Date {

   let (intHour, intMinute, time1) = getStuffFromTime(time: alarms[i].time, amOrPm: alarms[i].amOrPm)
   // this is my own function I made, the result intHour, and intMinute (ignore time1) are of type int. intHour is always between 0 and 23, intMinute is always between 0 and 59
   let gregorian = Calendar(identifier: .gregorian)
   var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: dateOpened)
   components.hour = intHour
   components.minute = intMinute
   var myDate = gregorian.date(from: components)
   print(myDate)
   // 2017-11-04 4:13:20 PM +0000
   myDate = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
   print(myDate)
   // 2017-11-05 5:13:20 PM +0000
}

正如您所看到的,它确实为myDate添加了一天,但它也增加了一个小时。有人知道它为什么这样做,或者我怎么能避免增加额外的小时?我只想在变量myDate中添加一天。我已经尝试过指定格里高利的TimeZone,但它没有效果。

0 个答案:

没有答案