Search code examples
iosiphoneswiftnsdateformatter

Weekday component issue


I'm trying to use weekday from calendar. I should receive Monday but somehow I'm receiving Tuesday. Any ideas why?

let date = Date(timeIntervalSince1970: 1519654139)
var calendar = Calendar(identifier: .gregorian)
calendar.locale = Locale(identifier: "en_US_POSIX")
calendar.timeZone = TimeZone(secondsFromGMT: 3600)!

let weekDayComponent = calendar.component(Calendar.Component.weekday, from: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE EEEE"
print("Date formatter says it's " + dateFormatter.string(from: date))
print("Weekday component is \(weekDayComponent)")

Console output:

Date formatter says it's Mon Monday
Weekday component is 2

[EDIT]: Why I'm receiving 2, not 1? yes, value of calendar.firstWeekday is 1.


Solution

  • Week in gregorian calendar starts with Sunday, therefore it is a correct behavior, 2 is Monday. Documentation clearly states that:

    Weekday units are the numbers 1 through n, where n is the number of days in the week. For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1.