I. Official methods
DateComponents
A date or time specified in terms of units (such as year, month, day, hour, and minute) to be evaluated in a calendar system and time zone.
The date or time specified in units to be calculated in the calendar system and time zone, such as years, months, days, hours, and minutes.
2. Implement
1. Calculate the difference between two string dates
func dateDiff(a) -> Int {
// Calculate the difference between two dates and return the difference of days
let formatter = DateFormatter(a)let calendar = Calendar.current
formatter.dateFormat = "yyyy-MM-dd"
let today = Date(a)// Start date
let startDate = formatter.date(from: "2021-06-08")
// End date
let endDate = formatter.date(from: "2021-06-09")
let diff:DateComponents = calendar.dateComponents([.day], from: startDate!, to: endDate!)
return diff.day!
}
Copy the code
2. Calculate the difference between the day and the day
func checkDiff(a) -> Int {
// Calculate the difference between two dates and return the difference of days
let formatter = DateFormatter(a)let calendar = Calendar.current
formatter.dateFormat = "yyyy-MM-dd"
/ / in the day
let today = Date(a)let startDate = formatter.date(from: formatter.string(from: today))
// Fixed date
let endDate = formatter.date(from: "2021-06-09")
let diff:DateComponents = calendar.dateComponents([.day], from: startDate!, to: endDate!)
return diff.day!
}
Copy the code
Blog links
Swift calculates the difference between the two dates