swift 3中的Unix时间戳转换问题

时间:2017-04-21 05:45:27

标签: swift

我正在尝试从服务器转换时间戳,它也正在转换,但只有月份出错。类似于时间戳是1492747393892并且它转换为21/03/17 - 12:03 PM但它应该是21/04/17 - 下午12:03 这是我的代码

var arriveTimestamp: Int 
if let timeStampToDate = arriveTimestamp {
                    let timeSt = Date(jsonTimeDate:"/Date(\(timeStampToDate))/")
                    let time = Date().dateTime(date: timeSt!)
                    valueLbl.text = time
                }

   init?(jsonTimeDate: String) {
    //        "/Date(1487058855745)/"

    let prefix = "/Date("
    let suffix = ")/"
    let scanner = Scanner(string: jsonTimeDate)

    // Check prefix:
    guard scanner.scanString(prefix, into: nil)  else { return nil }

    // Read milliseconds part:
    var milliseconds : Int64 = 0
    guard scanner.scanInt64(&milliseconds) else { return nil }
    // Milliseconds to seconds:
    var timeStamp = TimeInterval(milliseconds)/1000.0

    // Read optional timezone part:
    var timeZoneOffset : Int = 0
    if scanner.scanInt(&timeZoneOffset) {
        let hours = timeZoneOffset / 100
        let minutes = timeZoneOffset % 100
        // Adjust timestamp according to timezone:
        timeStamp += TimeInterval(3600 * hours + 60 * minutes)
    }

    // Check suffix:
    guard scanner.scanString(suffix, into: nil) else { return nil }

    // Success! Create NSDate and return.
    self.init(timeIntervalSince1970: timeStamp)
}

func dateTime(date: Date) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/mm/yy - hh:mm a"
    return dateFormatter.string(from: date as Date)
}

1 个答案:

答案 0 :(得分:2)

代码中的主要错误是月份的日期格式错误, 这应该是" MM"而不是" mm" (这是分钟)。

除此之外,你的方法太复杂了。所有你需要的 do是将时间戳(以毫秒为单位)除以1000 并致电Date(timeIntervalSince1970:)

let arriveTimestamp = 1492747393892
let date = Date(timeIntervalSince1970: TimeInterval(arriveTimestamp)/1000)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yy - hh:mm a"
let text = dateFormatter.string(from: date)

print(text) // 21/04/17 - 06:03 AM