-2

How to find get time in swift .

  • 1
    Please edit your question and show what you have tried and the issues you are facing. You should also improve your post and be more specific. What do you expect as result if one date is 11:59pm and the other is the next day 12:00am. Is it considered one day or zero? – Leo Dabus Jun 13 '20 at 04:16

1 Answers1

3

If your two dates are strings, convert them to Date objects (using a DateFormatter) and then you can use Calendar method dateComponents(_:from:to:) to get the number of days:

func days(from: String, to: String) -> Int? {
    let formatter = DateFormatter()
    formatter.dateFormat = "MM/dd/yyyy"

    guard
        let date1 = formatter.date(from: from),
        let date2 = formatter.date(from: to)
    else {
        return nil
    }

    return Calendar.current.dateComponents([.day], from: date1, to: date2).day
}
Rob
  • 392,368
  • 70
  • 743
  • 952
  • This might not return the exact number of days. If there is no time info it might get one day 1:00am (daylight savings) and the other day midnight. You should use noon time for this kind of calendrical calculations – Leo Dabus Jun 13 '20 at 06:54
  • Yiu should also set locale to “en_US_POSIX” when parsing fixed date formats. I would also set the calendar property just in case to avoid some daylight savings issues. https://stackoverflow.com/a/32408916/2303865 – Leo Dabus Jun 13 '20 at 06:58
  • try `func days(from: String, to: String) -> Int? { let formatter = DateFormatter() formatter.locale = Locale.init(identifier: "pt_BR") formatter.dateFormat = "MM/dd/yyyy" guard let date1 = formatter.date(from: from), let date2 = formatter.date(from: to) else { return nil } return Calendar.current.dateComponents([.day], from: date1, to: date2).day } days(from: "10/18/2015", to: "10/19/2015")` // nil – Leo Dabus Jun 13 '20 at 07:12
  • I have set the locate but to Brazil but it could be any – Leo Dabus Jun 13 '20 at 07:12
  • now add `formatter.calendar = .current` it will return 0 – Leo Dabus Jun 13 '20 at 07:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/215862/discussion-between-rob-and-leo-dabus). – Rob Jun 13 '20 at 07:21