【问题标题】:How to create a time stamp from nsdate(timeintervalsince1970)如何从 nsdate(timeintervalsince1970) 创建时间戳
【发布时间】:2017-09-09 00:26:50
【问题描述】:

我一直在寻找一段时间,并没有找到一个好的答案。我目前有当用户发布照片时,它需要一个 nsdate(timeIntervalSince1970) 并在上传到 Firebase 时将其作为一个值。一个问题,我将 nsdate 更改为 timeStamp 或 mins/hours/days 的当前方式,因为它被发布并不是很好,它不能纠正一天过去的时间,它只是显示它是在什么时间发布的。我希望我能得到答案或参考一种算法,该算法可以将 nsdate(timeIntervalSince1970) 更改为时间戳或字符串,它只告诉我它是在几小时前发布的,并且每 24 小时将其更改为 1 天(s )。我想我提前为问了一个简单的问题道歉。这是我当前的代码:

    if let seconds = posts[visibli.row].timeStamp {
        let time = NSDate(timeIntervalSince1970: TimeInterval(seconds))
        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm a"
        labelTime.text = formatter.string(from: time as Date)
    }

感谢您的帮助!

【问题讨论】:

  • 仅供参考 - 不要使用 NSDate。只需使用Date

标签: ios swift


【解决方案1】:

您正在寻找的是DateComponentsFormatter。您可以查看不同的格式化程序Foundation 提供,here.

如果您想要一个字符串来表示自给定日期以来经过的时间量,您可以这样说:

if let seconds = posts[visibli.row].timeStamp {
    let time = Date(timeIntervalSince1970: TimeInterval(seconds))
    let dateComponentsFormater = DateComponentsFormatter()
    dateComponentsFormater.unitsStyle = .positional
    let string = dateComponentsFormater.string(from: time, to: Date())
    labelTime.text = string
}

【讨论】:

  • 有没有办法从字符串中删除秒?贝尤尔夫
  • dateComponentsFormater.allowedUnits = [.day, .hour, .minute] 可以用来指定你想要的单位。
【解决方案2】:

当前时间戳为字符串。

 public class func getCurrentTimeStamp()->String{
        return String(describing: NSNumber(value: round(NSDate().timeIntervalSince1970 * 1000)))
    }

此函数使用获取当前时间戳。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 2016-05-05
    • 2022-07-26
    相关资源
    最近更新 更多