【问题标题】:Swift convert unix time to date and timeSwift 将 unix 时间转换为日期和时间
【发布时间】:2015-01-07 01:51:57
【问题描述】:

我当前的代码:

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 上运行。

【问题讨论】:

标签: ios swift time


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在 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),您将获得所需的字符串输出。

    【讨论】:

    • 这增加了比预期结果更多的复杂性。这只是将时间戳从静态 json 文件转换为可读格式。
    【解决方案3】:

    将时间戳转换为日期对象。

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

    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
    }
    

    【讨论】:

      【解决方案4】:

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

      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)                     
      }
      

      斯威夫特 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)                                
      }
      

      【讨论】:

      • 如果您只需要时间,则完全删除 dateFormatter.dateStyle 行或 // 将其删除。或者只是日期然后对 dateFormatter.timeStyle 做同样的事情。
      • @Cmag 查看 Swift 3 更新
      • ` dateFormatter.timeZone = NSTimeZone() as TimeZone!` 崩溃
      【解决方案5】:

      斯威夫特:

      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))
          }
      }
      

      【讨论】:

      • 恕我直言,最好是方便初始化。
      【解决方案6】:

      这是来自我的一个应用的有效 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)"
      }
      

      【讨论】:

        【解决方案7】:

        为了在 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 也很有帮助

        【讨论】:

        • ("1481721300" as! Double) 不会编译。您不能强制将 String 强制转换为 Double。
        • let Date = (Double("1627377130))!.getDateStringFromUTC() print(Date) 输出为 2021 年 7 月 27 日
        【解决方案8】:

        无论如何@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

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

        【讨论】:

          【解决方案9】:

          将 Unix 时间戳转换为所需格式很简单。让我们假设 _ts 是长的 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)")
          

          【讨论】:

            【解决方案10】:
            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)
            }
            

            【讨论】:

            • 我使用的方法显示时间为 12 小时,除非用户将手机设置为 24 小时,然后它显示为 24 小时。还可以在一个函数而不是两个函数中完成我需要的东西。你能解释一下你的答案有什么好处吗?
            • 我的示例显示的是太平洋标准时间。例如在美国使用 Am & Pm 标准。一些 Api(例如 forecast.io)提供了 unix 时间标准。
            • 修复了我自己的答案以显示我最终使用的完整代码。使用该代码,它会根据您的位置将 unix 时间转换为本地时间。此外,按照我对应用程序的编程方式,它将遵循手机设置 12 小时或 24 小时。
            【解决方案11】:

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

            let date = NSDate(timeIntervalSince1970: 1415637900)
            

            【讨论】:

            • 非常感谢!!我所要做的就是改变第二行,让 date = NSDate(timeIntervalSince1970: timeResult) 得到正确的结果。
            • @Nate Cook,这个答案错过了半个世纪:
            • 我不知道为什么,但是我得到纪元时间的服务器以毫秒为单位返回它,我必须将它除以 1000 才能使其工作......
            • @Honey 我也是。为什么是这样?。有人知道吗?
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-08-23
            • 1970-01-01
            • 2014-05-06
            • 2015-02-09
            • 1970-01-01
            • 2016-06-07
            • 2018-12-27
            相关资源
            最近更新 更多