Home > Enterprise >  How to convert 10digit int to date
How to convert 10digit int to date

Time:01-13

How to convert 1640704675 into date.

extension Date {
    var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }

    init(milliseconds:Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}

//Convert date to another formate.
func dateConvertion(date: Date, dateFormat: String) -> String {
    let dateFormater = DateFormatter()
    dateFormater.dateFormat = dateFormat
    dateFormater.locale = Locale(identifier: "en_US_POSIX")
    let dateStr = dateFormater.string(from: date)
    return dateStr
}

Try to convert 10 digit Int to Date //

if let modifiedDate = callValue?.updatedDate{
        let dateValue = String(modifiedDate).toDate(.isoDateTimeMilliSec) ?? Date()
        let finalDate = dateConvertion(date: dateValue, dateFormat: formaterMonthDateyear)
        print("finalDate \(finalDate)")
}

Its shown current date value when converting int value to date

CodePudding user response:

As mentioned in comment, it looks like your integer value is a number of seconds since 1970, not milliseconds. Just use the existing init(timeIntervalSince1970: TimeInterval) method, and cast your integer to a TimeInterval:

And call it like this:

print(Date(timeIntervalSince1970: TimeInterval(1640704675)))

As mentioned in a comment, that displays 2021-12-28 15:17:55 0000, which looks like a recent, valid date.

CodePudding user response:

You are converting from what's called epoch time, and based on number of digits, at least your example 1640704675 does not include milliseconds.

In iOS there's already an initializer for Date that matches that format: init(timeIntervalSince1970:)

So you don't need any new functions, simply call that initializer:

let epoch = Double(1640704675)
let date = Date(timeIntervalSince1970: epoch)

So your code becomes:

if let modifiedDate = callValue?.updatedDate{
        let dateValue = Date(timeIntervalSince1970: modifiedDate)
        let finalDate = dateConvertion(date: dateValue, dateFormat: formaterMonthDateyear)
        print("finalDate \(finalDate)")

Note that you may need to convert the modifiedDate into Double (by using Double(modifiedDate)), if it's coming in some different format. But don't convert it to string.

  •  Tags:  
  • Related