get yesterday's date in swift

You can get yesterday's date in Swift by using the Calendar and DateComponents classes. Here's the code:

main.swift
let calendar = Calendar.current
let yesterday = calendar.date(byAdding: .day, value: -1, to: Date())
101 chars
3 lines

This code creates a Calendar instance representing the current calendar, and uses it to calculate yesterday's date by subtracting one day (-1) from the current date (Date()).

Note that this code assumes a Gregorian calendar (the default for most locales). If you need to work with a different calendar, you'll need to create a Calendar instance with the appropriate Calendar.Identifier value.

gistlibby LogSnag