Convert Date to Integer in Swift

后端 未结 3 1307
暖寄归人
暖寄归人 2020-12-30 02:40

I am updating some of my old Swift 2 answers to Swift 3. My answer to this question, though, is not easy to update since the question specifically asks for NSDate

3条回答
  •  星月不相逢
    2020-12-30 03:01

    timeIntervalSince1970 is a relevant start time, convenient and provided by Apple.

    If u want the int value to be smaller, u could choose the relevant start time you like

    extension Date{
        var intVal: Int?{
            if let d = Date.coordinate{
                 let inteval = Date().timeIntervalSince(d)
                 return Int(inteval)
            }
            return nil
        }
    
    
        // today's time is close to `2020-04-17 05:06:06`
    
        static let coordinate: Date? = {
            let dateFormatCoordinate = DateFormatter()
            dateFormatCoordinate.dateFormat = "yyyy-MM-dd HH:mm:ss"
            if let d = dateFormatCoordinate.date(from: "2020-04-17 05:06:06") {
                return d
            }
            return nil
        }()
    }
    
    
    extension Int{
        var dateVal: Date?{
            // convert Int to Double
            let interval = Double(self)
            if let d = Date.coordinate{
                return  Date(timeInterval: interval, since: d)
            }
            return nil
        }
    }
    

    Use like this:

        let d = Date()
    
        print(d)
        // date to integer, you need to unwrap the optional
        print(d.intVal)
    
        // integer to date
        print(d.intVal?.dateVal)
    

提交回复
热议问题