Search code examples
iosswiftdatensdateformatter

How to get accuracy completion days count from input date


How to get accuracy completion days count from given input date

  func floatDifferenceDays() -> Double {
    let current = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let   inputDate : String = "2018-07-15 05:46:12"
    let input = dateFormatter.date(from: inputDate)
    var result = current.timeIntervalSince(input!)
    result = result / 86400
    return result
}

Its zero. since the cycle of days datecomonents.day till 31 and increments to Month followed by year.

How can get the days that cycle have taken place which not include year,months.

if given inputdate 12 hours back from current date its should return 0.5 days completed


Solution

  • I would suggest you use Calendar and DateComponents to get the correct elapsed time between two dates. This will cater for leap years and daylight savings time changes.

    E.g.

    let current = Date()
    let dateFormatter = DateFormatter()
    let calendar = Calendar.autoupdatingCurrent
    let timezone = TimeZone.autoupdatingCurrent
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let inputDate = "2018-07-15 05:46:12"
    if let input = dateFormatter.date(from: inputDate) {
        let components = calendar.dateComponents([.day,.hour], from: input, to: current)
        let days = Float(components.day ?? 0)
        let hours = Float(components.hour ?? 0)
        let elapsed = days + hours/24.0
        print("elapsed time is \(elapsed) days")
    }
    

    elapsed time is 366.25 days

    Note that this code assumes that the input string is in the "local" timezone; If it isn't you would need to make appropriate changes.