Search code examples
swiftcalendarnsdatensdatecomponents

get first day of week using Weeknumber in Swift


I am trying to get the first day of current week (say this week, i should be getting 2015-09-13).

However i cannot find the appropriate function in Apple's provided source code.

code should be something like this...

print(getFirstDay(40)) // Should print 27

func getFirstDay(weekNumber:Int)->Int?{
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    if let todayDate = formatter.dateFromString(weekNumber) {
        let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let myComponents = myCalendar.dateFromComponents(.weekOfYear)
        let date = myComponents.date
        return date
    } else {
        return nil
    }
}

However above code doesn't work (obviously) but it is something i was thinking of should be in the right direction.

How can i achieve this?

/* Not important */ I am trying to create a sort-of calendar app in a table View which is separated by Sections of 4 weeks, i want to know which date a new week starts at.


Solution

  •     func getFirstDay(weekNumber:Int)->String?{
            let Calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
            let dayComponent = NSDateComponents()
            dayComponent.weekOfYear = weekNumber
            dayComponent.weekday = 1
            dayComponent.year = 2015
            var date = Calendar.dateFromComponents(dayComponent)
    
            if(weekNumber == 1 && Calendar.components(.Month, fromDate: date!).month != 1){
                print(Calendar.components(.Month, fromDate: date!).month)
                dayComponent.year = 2014
                date = Calendar.dateFromComponents(dayComponent)
            }
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd-MM-yyyy"
            return String(dateFormatter.stringFromDate(date!))
        }
    

    Very rough code what i did so far.

    It works for finding the first day of the week ;)!