I have created some code which retrieves and formats the current date into the correct format and I have a second date which is a string. How can I calculate the days difference. I have read alot of posts howerver am very confused on how to implement it.
Current Code:
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let currentDateFormatted = formatter.string(from: date)
let endDate = "16.05.2018"
I have tried the following code however I am getting an error "Type of expression is ambiguous without more context".
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let currentDateFormatted = formatter.string(from: date)
let endDate = "16.05.2018"
let endDateFormatted= formatter.date(from: endDate)
let calendar = Calendar.current
let components = calendar.dateComponents([.day], from: currentDateFormatted, to: endDateFormatted)
=DAYS (end_date, start_date) They are the two dates between which we wish to calculate the number of days.
You need to convert the endDate string into a Date using the date formatter. Then pass date and the new Date to the dateComponents call. Then access the day property of the resulting components.
And use Calendar, not NSCalendar.
let startDate = Date()
let endDateString = "16.05.2018"
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
if let endDate = formatter.date(from: endDateString) {
let components = Calendar.current.dateComponents([.day], from: startDate, to: endDate)
print("Number of days: \(components.day!)")
} else {
print("\(endDateString) can't be converted to a Date")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With