Search code examples
swiftnscalendar

NSDate startOfDay is 4AM?


I'm trying to write a loop for every 10 minutes of a given 24 hour day, starting at midnight and ending at ten minutes before midnight. So I tried this...

    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))

The result for june is "2017-06-21 04:00:00 UTC". Now technically this is correct, my local day will be 4 AM UTZ, but the code I'm passing this into, from the Astronomical Almanac, already handles local/global conversion.

So then I tried this:

    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))

This produced the exact same result. What am I missing?


Solution

  • It seems that the date formatter does not use the timezone of the assigned calendar, and adding

    dateFormatter.timeZone = UTZCal.timeZone
    

    to your code makes it produce the expected result. But note that you can simplify the calculation to

    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