NSDate startOfDay 是凌晨 4 点?

NSDate startOfDay is 4AM?

我正在尝试在给定的 24 小时内每 10 分钟编写一个循环,从午夜开始到午夜前十分钟结束。所以我尝试了这个...

    let x = Calendar.current.component(.year, from: Date())
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat="dd-MM-yyyy"
    let june = dateFormatter.date(from: "21-06-" + String(x))

june 的结果是“2017-06-21 04:00:00 UTC”。现在从技术上讲这是正确的,我当地的一天是 UTZ 凌晨 4 点,但是我将其传递到天文年历中的代码已经处理了 local/global 转换。

然后我尝试了这个:

    var UTZCal = Calendar.current
    UTZCal.timeZone = TimeZone(abbreviation: "GMT")!
    let x = UTZCal.component(.year, from: Date())
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat="dd-MM-yyyy"
    dateFormatter.calendar = UTZCal
    let june = dateFormatter.date(from: "21-06-" + String(x))

这产生了完全相同的结果。我错过了什么?

日期格式化程序似乎没有使用 分配日历,并添加

dateFormatter.timeZone = UTZCal.timeZone

您的代码使其产生预期的结果。但请注意,你 可以简化计算到

var utzCal = Calendar(identifier: .gregorian)
utzCal.timeZone = TimeZone(secondsFromGMT: 0)!

let year = utzCal.component(.year, from: Date())
let june = DateComponents(calendar: utzCal, year: year, month: 6, day: 21).date!
print(june) // 2017-06-21 00:00:00 +0000