如何从swift中的时间戳获取日期格式

如何从swift中的时间戳获取日期格式,swift,timestamp,Swift,Timestamp,我想从时间戳中获取日期格式。因此,我从firebase数据库中获取时间戳。因此,当从firestore 2018-08-31T05:33:31.408Z检索时,我得到了这个输出。所以我想将时间戳格式化为“2018年8月”,上午11:39。所以我试着用这个代码来转换它 let timestamp = deyaPaybalance.value(forKey: "timestamp") as! NSArray print("timestamp is",timestamp) //let len = ti

我想从时间戳中获取日期格式。因此,我从firebase数据库中获取时间戳。因此,当从firestore 2018-08-31T05:33:31.408Z检索时,我得到了这个输出。所以我想将时间戳格式化为“2018年8月”,上午11:39。所以我试着用这个代码来转换它

let timestamp = deyaPaybalance.value(forKey: "timestamp") as! NSArray
print("timestamp is",timestamp)
//let len = timestamp.count
for element in timestamp {
    let ele = element
    let formatter = ISO8601DateFormatter()
    //print("date is",date1!)
    formatter.formatOptions = [.withFullDate,
                               .withTime,
                               .withDashSeparatorInDate,
                               .withColonSeparatorInTime]
    let date2 = formatter.date(from: ele as! String)
    print("timestamp with date is",date2!)
    print("element is",ele)
}

但我得到的是这种类型的输出2018-09-22 09:29:11+0000。那么如何解决这个问题呢。

您实际上是在将时间戳解析为日期对象。现在,如果希望date对象以任何其他方式格式化,请使用DateFormatter变量,设置格式化程序的dateFormat并从日期获取字符串。将日期转换为所需字符串的

let anotherFormatter = DateFormatter()
anotherFormatter.dateFormat = "MMM yyyy, h:mm a"
anotherFormatter.string(from: date2)

实际上,您正在将时间戳解析为日期对象。现在,如果希望date对象以任何其他方式格式化,请使用DateFormatter变量,设置格式化程序的dateFormat并从日期获取字符串。将日期转换为所需字符串的

let anotherFormatter = DateFormatter()
anotherFormatter.dateFormat = "MMM yyyy, h:mm a"
anotherFormatter.string(from: date2)

实际上,您正在将时间戳解析为日期对象。现在,如果希望date对象以任何其他方式格式化,请使用DateFormatter变量,设置格式化程序的dateFormat并从日期获取字符串。这将把日期转换为预期的字符串。实际上,您正在将时间戳解析为日期对象。现在,如果希望date对象以任何其他方式格式化,请使用DateFormatter变量,设置格式化程序的dateFormat并从日期获取字符串。将日期转换为所需字符串。确定。谢谢你,贾希多克。谢谢你,贾希德