get the date for the last day of this week in swift

Here's one way to get the date for the last day of the current week using Swift:

main.swift
let calendar = Calendar.current
let today = Date()

// Get the start of the current week.
var startOfWeek = Date()
_ = calendar.dateInterval(of: .weekOfMonth, start: &startOfWeek, interval: nil, for: today)

// Set the end of the week to be 6 days after the start.
var endOfWeek = calendar.date(byAdding: .day, value: 6, to: startOfWeek)!

// Make sure we're not in the future.
endOfWeek = min(endOfWeek, today)

print("Last day of the week: \(endOfWeek)")
457 chars
15 lines

This code uses the Calendar.current instance to get the start of the current week using dateInterval(of:interval:start:for:). It then sets the end of the week to be 6 days after the start using date(byAdding:value:to:). Finally, it checks that the end of the week is not in the future using min(:_) and prints the result.

gistlibby LogSnag