Nathan Berhe Nathan Berhe - 4 months ago 9
Swift Question

Get all dates for current week returns incorrect if the date is beginning of a month

This is a code i found online to get all dates for the current week based on today┬┤s date. If the date is the beginning of the month, for example Thursday September 01 2016 then it starts the week from Thursday and end the week at Wednesday September 07 2016. This is really bothering me because if the date is the end of the month; Sunday July 31 2016 then it will start on Monday and end on Sunday in that week which is exactly what i want.

This might be a duplicate but i spent a while looking at similar questions and i am still stuck.

Edit:
Is there a way to return all date for the current week based on the current date?(And if you have time, the next week as well?)

func formatDate(date: NSDate) -> String {
let format = "EEEE MMMM dd yyyy"
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(date)

}
// =======================================================================//
// THIS WEEK DATES //
// =======================================================================//
func formattedDaysInThisWeek() -> [String] {
// create calendar
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!

// today's date
let today = NSDate()
let todayComponent = calendar.components([.Day, .Month, .Year], fromDate: today)
let components = calendar.components([.Weekday], fromDate: today)



// range of dates in this week
let thisWeekDateRange = calendar.rangeOfUnit(.Day, inUnit:.WeekOfMonth, forDate:today)


// date interval from today to beginning of week
let dayInterval = thisWeekDateRange.location - todayComponent.day
print(thisWeekDateRange.location)
print(todayComponent.day)


// date for beginning day of this week, ie. this week's Sunday's date

if components.weekday == 1 {
print("Is a sunday")
let beginningOfWeek = calendar.dateByAddingUnit(.Day, value: -6, toDate: today, options: .MatchNextTime)

var formattedDays: [String] = []

for i in 0 ..< 7 {
let date = calendar.dateByAddingUnit(.Day, value: i, toDate: beginningOfWeek!, options: .MatchNextTime)!
formattedDays.append(formatDate(date))

}
return formattedDays
} else {
print("Not a sunday")
let beginningOfWeek = calendar.dateByAddingUnit(.Day, value: dayInterval, toDate: today, options: .MatchNextTime)

var formattedDays: [String] = []

for i in 1 ..< thisWeekDateRange.length + 1 {
let date = calendar.dateByAddingUnit(.Day, value: i, toDate: beginningOfWeek!, options: .MatchNextTime)!
formattedDays.append(formatDate(date))

}

return formattedDays
}


}

Answer

This solution checks if the current date is Monday.

If yes, it's the beginning of the week, if no, get back to the past Monday.

It uses also the formatDate function.

func formattedDaysInThisWeek() -> [String] {
  // create calendar
  let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!

  // today's date
  let today = NSDate()

  let weekday = calendar.component(.Weekday, fromDate: today)
  let beginningOfWeek : NSDate
  if weekday != 2 { // if today is not Monday, get back
    beginningOfWeek = calendar.nextDateAfterDate(today, matchingUnit: .Weekday, value: 2, options: [.MatchNextTime, .SearchBackwards])!
  } else { // today is Monday
    beginningOfWeek = calendar.startOfDayForDate(today)
  }
  var formattedDays = [String]()
  for i in 0..<7 {
    let date = calendar.dateByAddingUnit(.Day, value: i, toDate: beginningOfWeek, options: [])!
    formattedDays.append(formatDate(date))
  }
  return formattedDays
}
Comments