get first day of this week in swift

You can get the first day of the week in Swift by using the Calendar and DateComponents classes. Here's an example:

main.swift
let calendar = Calendar.current
let today = Date()
let components = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: today)
let startOfWeek = calendar.date(from: components)!
191 chars
5 lines

In this code, we first get the current calendar using the Calendar.current static property. Then we get the current date using the Date() initializer. We then use dateComponents(_:from:) to get the year for the week of the year and the week of the year components for the current date.

Finally, we use calendar.date(from:) to get the start of the week by combining the year for the week of the year and week of the year components with the time components set to midnight.

gistlibby LogSnag