swift计算时差的问题

swift problem on calculate time difference

我开发了一个函数来计算两个日期之间的时差,在函数下方将两个日期作为字符串给出

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
    
    
}

以及我正在使用的相应日期格式化程序

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
}

也尝试在每个 return 格式化程序之前添加:formatter.locale = Locale.current

所以现在的问题是,如果我在模拟器上尝试这段代码,它会完美运行,下面是使用模拟器在控制台中的输出:

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)

在物理设备上尝试时,输出是这样的:

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

我猜这与不同的语言环境有关,因为 MayMaggio 意大利语

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")

和结果

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