如何在iOS中将数据类型声明为时间戳-Swift

时间:2018-09-17 12:25:44

标签: swift firebase timestamp google-cloud-firestore

我是一个新的iOS程序。我正在创建一个与Firestore集成的简单对象。在Firestore中,我创建了集合,每个文档都包含许多字段。

我在文档中添加了Timestamp字段。当我在xcode中创建模型时,如何将变量声明为Timestamp,因为我需要基于tableViewTimestamp的数据进行排序。

Timestamp中的Firestore如下所示:

September 17, 2018 at 3:37:43 PM UTC+7

所以,我该如何编写程序并获得最新的Timestamp,如在Firestore中显示的那样

这是在编程中:

struct RecentCallModel {

var call_answered: Bool?
var call_extension: String?
var call_type: String?
var details: String?
var duration:  String?
var title: String?
// How can i declare as Timestamp
var timestamp: ???

init(call_answered: Bool, call_extension: String, call_type: String, details: String , duration: String, timestamp: String,  title: String) {

    self.call_answered = call_answered
    self.call_extension = call_extension
    self.call_type = call_type
    self.details = details
    self.title = title
 }


}

3 个答案:

答案 0 :(得分:2)

不熟悉Firebase。但是通常,在iOS中,我们将时间戳存储为TimeInterval,这些时间戳是Double的类型别名。

class func getDateOnly(fromTimeStamp timestamp: TimeInterval) -> String { 
  let dayTimePeriodFormatter = DateFormatter()
  dayTimePeriodFormatter.timeZone = TimeZone.current 
  dayTimePeriodFormatter.dateFormat = "MMMM dd, yyyy - h:mm:ss a z" 
  return dayTimePeriodFormatter.string(from: Date(timeIntervalSince1970: timestamp)) 
} 

答案 1 :(得分:2)

这是一种方法,我们如何快速获取当前日期和时间。而且您也可以将时间戳记声明为Double,但我不确定

// get the current date and time
let currentDateTime = Date()

// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long

// get the date time String from the date object
formatter.string(from: currentDateTime) 

答案 2 :(得分:1)

不确定您的问题明确意味着什么,但是通常将时间戳值声明为Double,类似var timestamp: Double。检索到的数据看起来类似于1537187800,可以使用以下帮助程序类将其转换为实际日期和/或时间

class DateAndTimeHelper {

static func convert(timestamp: Double, toDateFormat dateFormat: String) -> String {

        let date = Date(timeIntervalSince1970: timestamp)
        let dateFormatter = DateFormatter()
            dateFormatter.timeZone = NSTimeZone.local
            dateFormatter.locale = NSLocale.current
            dateFormatter.dateFormat = dateFormat

        return dateFormatter.string(from: date)

    }

}

可以使用以下语法

var timestamp: Double = 0.0

// Perform some database querying action in order to retrieve the actual timestamp value from the server
DateAndTimeHelper.convert(timestamp: timestamp, toDateFormat: DATE_FORMAT)

请注意,您应将DATE_FORMAT替换为您要遵循的格式。 here是可用格式的很好参考。

相关问题