I am implementing a timer that requires calculating the milliseconds of the user being inactive and calculate the difference and recover the timer. Since there is no milliseconds option in dateComponents, I used nanoseconds instead, however, when I try to calculate the nanoseconds interval between two dates, I get the same results every time (current date is changing, should get different result), if I change the nanosecond to second, it works. I executed it twice to experiment.
let d1 = Date()
let df = DateFormatter()
df.dateFormat = "y-MM-dd H:m:ss.SSSS"
let d2 = df.date(from: "2021-05-03 9:30:00.1234")!
print(df.string(from: d1))
print(df.string(from: d2))
print(Calendar.current.dateComponents([.second], from: d1, to: d2).second!)
// result1: "85573"
// result2: "85067"
When I use nanosecond
let d1 = Date()
let df = DateFormatter()
df.dateFormat = "y-MM-dd H:m:ss.SSSS"
let d2 = df.date(from: "2021-05-03 9:30:00.1234")!
print(df.string(from: d1))
print(df.string(from: d2))
print(Calendar.current.dateComponents([.nanosecond], from: d1, to: d2).nanosecond!)
// result1: "2147483647"
// result2: "2147483647"