I have two dates in 24 hours formate like (dd-MMM-yyyy HH:mm). I want to get a difference between these two dates.
My Code : This is getting only dates, I want a number
struct EventDate {
var monthYear: [String]?
var monthNumber: [String]?
var year: [String]?
var month: [String]?
init(monthYear: [String]?,monthNumber:[String]?,year:[String]?,month:[String]?) {
self.monthYear = monthYear
self.monthNumber = monthNumber
self.year = year
self.month = month
}
}
func getMonthAndYearBetween(from start: String, to end: String) -> EventDate {
var monthYear: [String] = []
var monthNumber: [String] = []
var years: [String] = []
var months: [String] = []
let format = DateFormatter()
format.dateFormat = "dd/MM/yyyy"
guard let startDate = format.date(from: start),
let endDate = format.date(from: end) else {
return EventDate(monthYear: [], monthNumber: [], year: [], month: [])
}
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(Set([.month]), from: startDate, to: endDate)
var allDates: [String] = []
let dateRangeFormatter = DateFormatter()
dateRangeFormatter.dateFormat = "MMM yyyy"
for i in 0 ... (components.month! + 1) {
guard let date = calendar.date(byAdding: .month, value: i, to: startDate) else {
continue
}
let formattedDate = dateRangeFormatter.string(from: date)
allDates += [formattedDate]
let df = DateFormatter()
df.dateFormat = "MMM yyyy"
let monyr = df.string(from: date)
monthYear.append(monyr)
df.dateFormat = "MM"
let monNO = df.string(from: date)
monthNumber.append(monNO)
df.dateFormat = "yyyy"
let yr = df.string(from: date)
years.append(yr)
df.dateFormat = "MMM"
let mon = df.string(from: date)
months.append(mon)
}
return EventDate(monthYear: monthYear, monthNumber: monthNumber, year: years, month: months)
}
you can get like this
let eventDate = Date().getMonthAndYearBetween(from: startDate, to: endDate)