get the date 5 years ago in swift

To get the date 5 years ago in Swift, you can use the Calendar and DateComponents APIs to subtract 5 years from the current date:

main.swift
let calendar = Calendar.current
let fiveYearsAgo = calendar.date(byAdding: .year, value: -5, to: Date())
105 chars
3 lines

Here, we're creating a Calendar instance to work with, and then using the date(byAdding:value:to:) method to subtract 5 years (-5) from the current date (Date()). The result is returned as an optional Date, which we can safely unwrap or handle with optional binding as needed.

Note that the resulting Date object will include the current time as well as the date – if you want to ignore the time and just work with the date components, you can use the dateComponents(_:from:) method to extract just the year, month, and day values:

main.swift
let dateComponents = calendar.dateComponents([.year, .month, .day], from: fiveYearsAgo!)
let fiveYearsAgoDateOnly = calendar.date(from: dateComponents)!
153 chars
3 lines

Here, we're using the dateComponents(_:from:) method to extract the year, month, and day components from the fiveYearsAgo date. Then, we're using the date(from:) method to create a new date object with just those components, effectively setting the time to midnight on that day. Again, note that both of these methods return optional values that need to be handled appropriately.

gistlibby LogSnag