I'm trying to calculate the Date
(NSDate
) instance that corresponds to the first day of the current month (I do not care about the time).
I am using this code (Swift 3):
let gregorian = Calendar(identifier: .gregorian)
let today = Date()
var dateComponents = gregorian.dateComponents([.era, .year, .month], from: today)
dateComponents.day = 1
guard let firstDayOfTheMonth = gregorian.date(from: dateComponents) else {
return
}
On the debugger, today
gives me the correct value of Date 2016-08-18 06:52:39 UTC
. However, firstDayOfTheMonth
gives: Date 2016-07-31 15:00:00 UTC
, that is, the last day of the previous month.
Obviously I'm off by one, but can't figure out why.
What is worse, when I try to get the weekday, I get the correct value of 2 (Monday, for August 1st):
// Sun = 1, Mon = 2, Wed = 3, ...
guard let firstWeekDay = gregorian.dateComponents([.weekday], from: firstDayOfTheMonth).weekday else {
return
}
...so, What's going on?