To get the date 5 months ago in Swift, you can use the Calendar
and DateComponents
classes to subtract 5 months from the current date. Here's an example code snippet:
main.swift182 chars7 lines
In this example, we first create an instance of the Calendar
class. We then create an instance of DateComponents
and set the month
property to -5, indicating that we want to subtract 5 months. We then use the date(byAdding:to:)
method of the Calendar
class to subtract the specified number of months from the current date. Finally, we print out the resulting date.
Note that the date(byAdding:to:)
method returns an optional Date
object, so we use optional binding (if let
) to safely unwrap the result.
gistlibby LogSnag