Date to milliseconds and back to date in Swift

后端 未结 9 2078
深忆病人
深忆病人 2020-11-29 01:53

I am taking the current time, in UTC, and putting it in nanaoseconds and then I need to take the nanoseconds and go back to a date in local time. I am able to do get the tim

9条回答
  •  Happy的楠姐
    2020-11-29 02:19

    @Prashant Tukadiya answer works. But if you want to save the value in UserDefaults and then compare it to other date you get yout int64 truncated so it can cause problems. I found a solution.

    Swift 4:

    You can save int64 as string in UserDefaults:

    let value: String(Date().millisecondsSince1970)
    let stringValue = String(value)
    UserDefaults.standard.set(stringValue, forKey: "int64String")
    

    Like that you avoid Int truncation.

    And then you can recover the original value:

    let int64String = UserDefaults.standard.string(forKey: "int64String")
    let originalValue = Int64(int64String!)
    

    This allow you to compare it with other date values:

    let currentTime = Date().millisecondsSince1970
    let int64String = UserDefaults.standard.string(forKey: "int64String")
    let originalValue = Int64(int64String!) ?? 0 
    
    if currentTime < originalValue {
         return false
    } else {
         return true
    }
    

    Hope this helps someone who has same problem

提交回复
热议问题