繁体   English   中英

如何从nsdate(timeintervalsince1970)创建时间戳

[英]How to create a time stamp from nsdate(timeintervalsince1970)

我已经搜索了一段时间,却没有找到一个好的答案。 我目前有一个用户发布照片时,它需要一个nsdate(timeIntervalSince1970)并将其作为值上传到Firebase时。 一个问题是,自发布日期以来,我将nsdate更改为timeStamp或分钟/小时/天的当前方法不是图灵过渡,它不能正确地校正一天的时间,它只是显示发布时间。 我希望我能得到一个答案或引用一个算法,该算法可以将nsdate(timeIntervalSince1970)更改为timeStamp或字符串,该时间戳或字符串仅使我知道发布了多少小时,并且每24小时将其更改为1天)。 我想我提前问了一个简单的问题表示歉意。 这是我当前的代码:

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

感谢您的任何帮助!

您正在寻找的是DateComponentsFormatter 您可以在此处查看 Foundation提供的不同格式器

如果您要使用一个字符串来表示自给定日期以来已过去的时间,则可以这样说:

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
}

当前时间戳记为字符串。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM