Taz questions his sanity:
The issue is that when I compute the date the date is fine, but the time on the date is set to 6 hours ahead. I am stumpped as to why?
@twoStraws notes that Dates
are hard! See-> Working with Dates
You need to understand the differences between Date
and Calendar
.
Apple documentation says this about Date
:
The Date structure provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date. Use date values with DateFormatter instances to create localized representations of dates and times and with Calendar instances to perform calendar arithmetic.
Here's some code for you to paste into Playgrounds. (You ARE using Playgrounds, yes?!)
// Fun with Dates and Calendars!
import Foundation
let myCalendar = Calendar.current
myCalendar.dateComponents([.timeZone], from: Date()) // timeZone: America/New_York
let rightNow = Date()
let howManyDays = 4
// Check values
rightNow.description // notice the time is a UTC value. Dates don't know timeZones.
let newDateInPast = myCalendar.date(byAdding: .day, value: -howManyDays, to: rightNow)
let dateComponents = myCalendar.dateComponents([.month, .day, .year, .hour, .minute, .timeZone], from: newDateInPast!)
var mergedComponents = DateComponents(calendar: myCalendar,
timeZone: dateComponents.timeZone,
year: dateComponents.year,
month: dateComponents.month,
day: dateComponents.day,
hour: dateComponents.hour,
minute: dateComponents.minute)
// Double check your assumptions!
mergedComponents.year
mergedComponents.month
mergedComponents.day
mergedComponents.hour
mergedComponents.minute
mergedComponents.timeZone // Should be the same as your default calendar.
let newDate = myCalendar.date(from: mergedComponents) // creating from the same calendar
newDate?.description // notice the time is a UTC value. Dates don't know timeZones.
From this you can see that your Calendar is synchronized with you Mac's local time zone. Dates, on the otherhand, are just points in time stored and calculated as UTC values. As the Apple documentation states:
Use date values with DateFormatter
instances to create localized representations of dates and times