Home > Software engineering >  Getting unexpected date from day formatter using weekOfYear
Getting unexpected date from day formatter using weekOfYear

Time:04-30

I'm trying to get the start of the week using the current week and my return value is a week off. For example, if I input weekNumber 17 I would expected April 25th to be returned based off this, but I'm getting back April 17th.

I did check out the following post and that is where I got the function below. get first day of week using Weeknumber in Swift

func getFirstDay(WeekNumber weekNumber:Int, CurrentYear currentYear: Int)->String?{
    let Calendar = NSCalendar(calendarIdentifier: .gregorian)!
    var dayComponent = DateComponents()
    dayComponent.weekOfYear = weekNumber
    dayComponent.weekday = 1
    dayComponent.year = currentYear
    var date = Calendar.date(from: dayComponent)

    if(weekNumber == 1 && Calendar.components(.month, from: date!).month != 1){
        dayComponent.year = currentYear - 1
        date = Calendar.date(from: dayComponent)
    }
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy/MM/dd"
    return String(dateFormatter.string(from: date!))
}

CodePudding user response:

There are a few issues

  • For week numbers use always the ISO8601 calendar.
  • For week numbers the correct year property is yearForWeekOfYear.
  • In your code the week starts on Sunday (1), the linked site refers to Monday.
  • In Swift use native Calendar.
  • In the last line the String initializer is redundant.
  • Don't force unwrap dates.

func getFirstDay(weekNumber:Int, currentYear: Int) -> String? {
    let calendar = Calendar(identifier: .iso8601)
    var dayComponent = DateComponents()
    dayComponent.weekOfYear = weekNumber
    dayComponent.yearForWeekOfYear = currentYear
    guard let date = calendar.date(from: dayComponent) else { return nil }
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy/MM/dd"
    return dateFormatter.string(from: date)
}
  • Related