0

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?

Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
  • The result is correct. `2016-07-31 15:00:00 UTC` is `2016-08-01` in *your timezone*. (NS)Dates are an absolute point in time without knowledge of a timezone. Printing a Date always uses UTC. – Martin R Aug 18 '16 at 07:10
  • You are right; I checked this answer (http://stackoverflow.com/a/8467038/433373) in the duplicate question, and as suggested printed the formatted dates to the console instead of watching them in the debugger. Now the first day of the month appears as "2016-08-01". I'm in JST (+0900). – Nicolas Miari Aug 18 '16 at 07:14
  • Apart from the issue the recommended method to calculate the first day of the month is `rangeOfUnit(:startDate:interval:forDate:)` of `NSCalendar` – vadian Aug 18 '16 at 08:05

0 Answers0