Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate days between 2 dates

Tags:

swift

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)
like image 723
user9802387 Avatar asked May 16 '18 20:05

user9802387


People also ask

What is the formula to calculate days?

=DAYS (end_date, start_date) They are the two dates between which we wish to calculate the number of days.


1 Answers

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")
}
like image 129
rmaddy Avatar answered Sep 20 '22 14:09

rmaddy