I am trying to put the dates of the beginning of the week in a app. However in 2017, this results in un-expected behavior, as this year has the week '1' 2 times in it,
starting Sunday Jan 1st, and Sun Dec 31. My program finds the latter. Giving me the result of '01-01-2018' where is should be, '02-01-2017'
How can i make sure my program finds the first date available?
this is my code:
getFirstDay(Int(weekNummer)!, year: yearWrap)
func getFirstDay(weekNumber:Int, year:Int)->String?{
let Calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let dayComponent = NSDateComponents()
dayComponent.weekOfYear = weekNumber
dayComponent.weekday = 2
dayComponent.year = year
var date = Calendar.dateFromComponents(dayComponent)
if ((weekNumber == 1 || weekNumber == 52 || weekNumber == 53) && Calendar.components(.Month, fromDate: date!).month != 1 ){
dayComponent.year = year - 1
date = Calendar.dateFromComponents(dayComponent)
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
return String(dateFormatter.stringFromDate(date!))
}
Let do NSCalendar
the complete date math
func firstDayOfWeek(week: Int, inYear year : Int) -> NSString {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let components = NSDateComponents()
components.weekOfYear = week
components.yearForWeekOfYear = year
components.weekday = 2 // First weekday of the week (Sunday = 1)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let date = calendar.dateFromComponents(components)!
return dateFormatter.stringFromDate(date)
}
firstDayOfWeek(1, inYear : 2017) // 02-01-2017
firstDayOfWeek(1, inYear : 2018) // 01-01.2018