get the date 5 weeks ago in swift

You can use Calendar and DateComponents to subtract a certain number of weeks from the current date and get the date from 5 weeks ago in Swift. Here's an example:

main.swift
let calendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.weekOfYear = -5
let fiveWeeksAgo = calendar.date(byAdding: dateComponents, to: Date())
172 chars
5 lines

In the first line, we get the current Calendar instance. Then we create a DateComponents object with the number of weeks we want to subtract, which is -5.

Finally, we use the date(byAdding:to:) method of Calendar to subtract the dateComponents from the current date and get the date from 5 weeks ago. The result is an optional Date object, so you may need to unwrap it before using it.

gistlibby LogSnag