0

I have problems handling local time dates for my app in Swift. I would like to create today's Date at midnight and another instance at 23:59. Basically 2 dates to cover the whole current day (the idea is to load all of today's calendar entries). My code in playground:

import Foundation

let dateFormatter = DateFormatter()
let date = Date()
dateFormatter.dateFormat = "yyyy-MM-dd"


let todayStartDate = dateFormatter.date(from: dateFormatter.string(from: date))
let todayEndDate = dateFormatter.date(from: dateFormatter.string(from: Calendar.current.date(byAdding: .day, value: 1, to: date)!))


print(todayStartDate!)
print(todayEndDate!)

I end up having the time in there:

"Jan 27, 2018 at 12:00 AM"

Output of the print:

"2018-01-26 23:00:00 +0000\n"

  • Everything is correct. Printing a `Date` always uses the GMT timezone, compare e.g. https://stackoverflow.com/questions/39937019/nsdate-or-date-shows-the-wrong-time. – So "2018-01-26 23:00:00 +0000" is midnight of 2018-01-27 in your timezone. – Martin R Jan 27 '18 at 11:16

1 Answers1

0

The answer – as already mentioned in the comments – is: print displays Date instances in GMT. 2018-01-26 23:00:00 +0000 is the same point in time as 2018-01-27 00:00:00 +0100

Apart from that I'd like to suggest a much more reliable way to get todayStartDate and todayEndDate using Calendar's powerful date math skills.

let calendar = Calendar.current
var todayStartDate = Date()
var interval = TimeInterval()
calendar.dateInterval(of: .day, start: &todayStartDate, interval: &interval, for: Date())
let todayEndDate = calendar.date(byAdding: .second, value: Int(interval-1), to: todayStartDate)!

print(todayStartDate)
print(todayEndDate)
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thanks a lot it makes sense. The only thing i'm wondering is that todayStartDate is given with the actual time, if my calendar entry occurred earlier, it might not loaded. – CraneDuitre Jan 27 '18 at 11:59
  • `todayStartDate` is declared as an inout pointer, the initial value is irrelevant. The actual date representing midnight today will be set in the `dateInterval(of:` line. The time portion of the date is set to zero unless there is no `0:00:00` today in the local time zone for example in Brazil at daylight savings change in fall. In this case the time is set to the actual first second of the date. – vadian Jan 27 '18 at 12:27