0ndre_ 0ndre_ - 2 months ago 20
Swift Question

How to get Monday 00:00 of current week? Swift 3

I'm trying to return Monday 00:00 from my date. This is my code:

func getMonday(myDate: Date) -> Date {
let cal = Calendar.current
let comps = cal.dateComponents([.weekOfYear, .yearForWeekOfYear], from: myDate)
let beginningOfWeek = cal.date(from: comps)!
return beginningOfWeek
}


My problem is that it does not return Monday 00:00 , but Saturday 22:00.

Example:

let monday1 = getMonday(myDate: date) //date is: 2016-10-04 17:00:00
print(monday1) //Prints: 2016-10-01 22:00:00 (Saturday)


My question is:

How to return Monday 00:00 from
myDate
?

Thank you very much.

Answer

Your code returns the first day in the given week, that may be a Sunday or Monday (or perhaps some other day), depending on your locale.

If you want Monday considered to be the first weekday then set

cal.firstWeekDay = 2

If you want the Monday of the given week, independent of what the start of the week is, then set comps.weekday = 2:

func getMonday(myDate: Date) -> Date {
    let cal = Calendar.current
    var comps = cal.dateComponents([.weekOfYear, .yearForWeekOfYear], from: myDate)
    comps.weekday = 2 // Monday
    let mondayInWeek = cal.date(from: comps)!
    return mondayInWeek
}

Note that printing a Date always uses the GMT time zone, you'll need a date formatter to print the result according to your local time zone. Example:

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm"

let now = Date()
print(df.string(from: now)) // 2016-10-02 20:16

let monday1 = getMonday(myDate: now)
print(df.string(from: monday1)) // 2016-09-26 00:00