簡體   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