Search code examples
swiftdatedateformatter

swift problem on calculate time difference


I have develop a function that calculate the time difference between two date giving the two date as string here below the function

func calculateTimeDifference(startDate: String, endDate: String) -> Int {
    print("START DATE 1: \(startDate)")
    print("END DATE 1: \(endDate)")
    let startDate = dateTimeFormatter.date(from: startDate)
    let endDate = dateTimeFormatter.date(from: endDate)
    print("START DATE 2: \(startDate)")
    print("END DATE 2: \(endDate)")
    
    guard let startDate = startDate,
          let endDate = endDate else {
        print("return 1")
              return 0
          }
            
    let dateDifference = Calendar.current.dateComponents([.minute], from: startDate, to: endDate)
    let minuteDifference = dateDifference.minute
    
    guard let minuteDifference = minuteDifference else {
        print("return 2")
        return 0
    }
    
    //timeDifference = minuteDifference
    print("TIME DIFFERENCE: \(minuteDifference)")
    return minuteDifference
    
    
}

and the corresponding date formatter that I'm using

var dateFormatter : DateFormatter {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    return formatter
}
var timeFormatter : DateFormatter {
    let formatter = DateFormatter()
    formatter.timeStyle = .short
    return formatter
}

var dateTimeFormatter: DateFormatter {
    let formatter = DateFormatter()
    formatter.dateFormat = "d, MMM y, HH:mm"
    return formatter
}

also try too add before each return formatter: formatter.locale = Locale.current

so now the problem is if I try this code on the simulator it works perfectly this below is the output in console using the simulator:

START DATE 1: 13, mag 2022, 11:36
END DATE 1: 13, mag 2022, 12:06
START DATE 2: Optional(2022-05-13 09:36:00 +0000)
END DATE 2: Optional(2022-05-13 10:06:00 +0000)

when try on physical device the output is this:

START DATE 1: 13, mag 2022, 11:36
END DATE 1: 13, mag 2022, 12:06
START DATE 2: nil
END DATE 2: nil

Solution

  • I guess this related to different locale, as May is Maggio italian

    var dateTimeFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "d, MMM y, HH:mm"
        formatter.locale = .init(identifier: "it_CH") // for italian locale
        return formatter
    }
    calculateTimeDifference(startDate: "13, mag 2022, 11:36", endDate: "13, mag 2022, 12:06")
    

    and the results

    START DATE 1: 13, mag 2022, 11:36
    END DATE 1: 13, mag 2022, 12:06
    START DATE 2: Optional(2022-05-13 09:36:00 +0000)
    END DATE 2: Optional(2022-05-13 10:06:00 +0000)
    TIME DIFFERENCE: 30