我想创建2个日期。第一次是90天前,第二次是现在。我可以得到90天前的日期,但我需要它的时间是00:00:00 +0000,我似乎无法摆脱或将时间归零。它总是以23:00:00 +0000的形式出现。90天前的日期似乎也不一样?
这是我正在使用的代码。
print("LAST NINETY DAYS")
let components = Calendar.current.dateComponents([.year, .month], from: Date())
let now = Calendar.current.date(from: components)!
print(now)
//have to zero out the time
let days90 = Calendar.current.date(byAdding: .day, value: -90, to: now) ?? Date()
var components2 = Calendar.current.dateComponents([.year, .month], from: days90)
components2.hour = 0
components2.minute = 0
components2.second = 0
let now2 = Calendar.current.date(from: components2)!
print(now2)
print(Date())
firstAndLastDateObj.firstDate = now2
firstAndLastDateObj.lastDate = Date()
要在UTC中单独工作,您必须将日历的时区设置为UTC。
创建Calendar
的自定义实例:
var cal = Calendar(identifier: .gregorian)
cal.timeZone = TimeZone(secondsFromGMT: 0)!
然后得到当前日期的午夜,并计算90天前
let todayMidnight = cal.startOfDay(for: Date())
let ninetyDaysAgo = cal.date(byAdding: .day, value: -90, to: todayMidnight)!