Swift将unix时间转换为日期和时间

时间:2014-11-10 17:15:44

标签: ios swift time

我目前的代码:

if  let var timeResult = (jsonResult["dt"] as? Double) {
    timeResult = NSDate().timeIntervalSince1970
    println(timeResult)
    println(NSDate())
}

结果:

println(timeResult) = 1415639000.67457

println(NSDate()) = 2014-11-10 17:03:20 +0000只是为了测试NSDate提供的内容。

我希望第一个看起来像最后一个。 dt的值= 1415637900。

另外,我如何调整时区?在 iOS 上运行。

11 个答案:

答案 0 :(得分:91)

您可以使用NSDate(withTimeIntervalSince1970:)初始化程序获取具有该值的日期:

let date = NSDate(timeIntervalSince1970: 1415637900)

答案 1 :(得分:37)

要将日期显示为当前时区,我使用了以下内容。

if let timeResult = (jsonResult["dt"] as? Double) {
     let date = NSDate(timeIntervalSince1970: timeResult)
     let dateFormatter = NSDateFormatter()
     dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
     dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
     dateFormatter.timeZone = NSTimeZone()
     let localDate = dateFormatter.stringFromDate(date)
}

Swift 3.0版本

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = self.timeZone
    let localDate = dateFormatter.string(from: date)                     
}

Swift 5

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = .current
    let localDate = dateFormatter.string(from: date)                                
}

答案 2 :(得分:29)

将Unix时间戳转换为所需格式非常简单。假设_ts是long

中的Unix时间戳
let date = NSDate(timeIntervalSince1970: _ts)

let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"

 let dateString = dayTimePeriodFormatter.stringFromDate(date)

  print( " _ts value is \(_ts)")
  print( " _ts value is \(dateString)")

答案 3 :(得分:10)

为了管理 Swift 3 中的日期,我最终得到了这个辅助函数:

extension Double {
    func getDateStringFromUTC() -> String {
        let date = Date(timeIntervalSince1970: self)

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US")
        dateFormatter.dateStyle = .medium

        return dateFormatter.string(from: date)
    }
}

这样一来,只要你需要它就很容易使用 - 在我看来是转换字符串:

("1481721300" as! Double).getDateStringFromUTC() // "Dec 14, 2016"

参考DateFormatter文档以获取有关格式化的更多详细信息(请注意,某些示例已过期)

我发现this article也非常有用

答案 4 :(得分:7)

以下是我的某个应用中的 Swift 3 解决方案。

/**
 * 
 * Convert unix time to human readable time. Return empty string if unixtime     
 * argument is 0. Note that EMPTY_STRING = ""
 *
 * @param unixdate the time in unix format, e.g. 1482505225
 * @param timezone the user's time zone, e.g. EST, PST
 * @return the date and time converted into human readable String format
 *
 **/

private func getDate(unixdate: Int, timezone: String) -> String {
    if unixdate == 0 {return EMPTY_STRING}
    let date = NSDate(timeIntervalSince1970: TimeInterval(unixdate))
    let dayTimePeriodFormatter = DateFormatter()
    dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
    dayTimePeriodFormatter.timeZone = NSTimeZone(name: timezone) as TimeZone!
    let dateString = dayTimePeriodFormatter.string(from: date as Date)
    return "Updated: \(dateString)"
}

答案 5 :(得分:5)

func timeStringFromUnixTime(unixTime: Double) -> String {
    let date = NSDate(timeIntervalSince1970: unixTime)

    // Returns date formatted as 12 hour time.
    dateFormatter.dateFormat = "hh:mm a"
    return dateFormatter.stringFromDate(date)
}

func dayStringFromTime(unixTime: Double) -> String {
    let date = NSDate(timeIntervalSince1970: unixTime)
    dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(date)
}

答案 6 :(得分:3)

<强>夫特:

extension Double {
    func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = dateStyle
        dateFormatter.timeStyle = timeStyle
        return dateFormatter.string(from: Date(timeIntervalSince1970: self))
    }
}

答案 7 :(得分:1)

无论如何@Nate Cook's答案已被接受,但我希望以更好的日期格式改进它。

Swift 2.2 ,我可以获得所需的格式化日期

//TimeStamp
let timeInterval  = 1415639000.67457
print("time interval is \(timeInterval)")

//Convert to Date
let date = NSDate(timeIntervalSince1970: timeInterval)

//Date formatting
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let dateString = dateFormatter.stringFromDate(date)
print("formatted date is =  \(dateString)")

结果是

  

时间间隔 1415639000.67457

     

格式化日期= = 10,2014年11月17:03:PM

答案 8 :(得分:1)

将时间戳转换为Date对象。

如果时间戳记对象无效,则返回当前日期。

class func toDate(_ timestamp: Any?) -> Date? {
    if let any = timestamp {
        if let str = any as? NSString {
            return Date(timeIntervalSince1970: str.doubleValue)
        } else if let str = any as? NSNumber {
            return Date(timeIntervalSince1970: str.doubleValue)
        }
    }
    return nil
}

答案 9 :(得分:1)

在Swift 5中

使用此实现,您只需要给定纪元时间作为参数,然后将输出显示为(1秒前,2分钟前,依此类推)。

func setTimestamp(epochTime: String) -> String {
    let currentDate = Date()
    let epochDate = Date(timeIntervalSince1970: TimeInterval(epochTime) as! TimeInterval)

    let calendar = Calendar.current

    let currentDay = calendar.component(.day, from: currentDate)
    let currentHour = calendar.component(.hour, from: currentDate)
    let currentMinutes = calendar.component(.minute, from: currentDate)
    let currentSeconds = calendar.component(.second, from: currentDate)

    let epochDay = calendar.component(.day, from: epochDate)
    let epochMonth = calendar.component(.month, from: epochDate)
    let epochYear = calendar.component(.year, from: epochDate)
    let epochHour = calendar.component(.hour, from: epochDate)
    let epochMinutes = calendar.component(.minute, from: epochDate)
    let epochSeconds = calendar.component(.second, from: epochDate)

    if (currentDay - epochDay < 30) {
        if (currentDay == epochDay) {
            if (currentHour - epochHour == 0) {
                if (currentMinutes - epochMinutes == 0) {
                    if (currentSeconds - epochSeconds <= 1) {
                        return String(currentSeconds - epochSeconds) + " second ago"
                    } else {
                        return String(currentSeconds - epochSeconds) + " seconds ago"
                    }

                } else if (currentMinutes - epochMinutes <= 1) {
                    return String(currentMinutes - epochMinutes) + " minute ago"
                } else {
                    return String(currentMinutes - epochMinutes) + " minutes ago"
                }
            } else if (currentHour - epochHour <= 1) {
                return String(currentHour - epochHour) + " hour ago"
            } else {
                return String(currentHour - epochHour) + " hours ago"
            }
        } else if (currentDay - epochDay <= 1) {
            return String(currentDay - epochDay) + " day ago"
        } else {
            return String(currentDay - epochDay) + " days ago"
        }
    } else {
        return String(epochDay) + " " + getMonthNameFromInt(month: epochMonth) + " " + String(epochYear)
    }
}


func getMonthNameFromInt(month: Int) -> String {
    switch month {
    case 1:
        return "Jan"
    case 2:
        return "Feb"
    case 3:
        return "Mar"
    case 4:
        return "Apr"
    case 5:
        return "May"
    case 6:
        return "Jun"
    case 7:
        return "Jul"
    case 8:
        return "Aug"
    case 9:
        return "Sept"
    case 10:
        return "Oct"
    case 11:
        return "Nov"
    case 12:
        return "Dec"
    default:
        return ""
    }
}

如何拨打电话?

setTimestamp(epochTime: time),您将获得所需的输出作为字符串。

答案 10 :(得分:-1)

  

对我来说:将来自API的时间戳转换为有效日期:

`let date = NSDate.init(fromUnixTimestampNumber: timesTamp /* i.e 1547398524000 */) as Date?`