使用时间戳记功能将特定日期和时间保存到Firestore数据库-Swift 4 [英] Save specific date and times to Firestore database using the timestamp feature - Swift 4
问题描述
如何在swift 4中创建不是当前日期的日期对象?例如,2019年12月3日下午2:35.然后,如何将该对象作为时间戳写到Firestore数据库中的文档中?
您可以创建一个DateFormatter对象,以将本机Date对象来回转换为字符串,并将日期指定为字符串,但是我不建议这样做.>
看看 Calendar
类和 DateComponents
类.带有签名的 Calendar
函数
func date(来自组件:DateComponents)->日期?
让您使用 DateComponents
对象创建日期.
所以您可以使用如下代码:
让日历= Calendar.current让组件= DateComponents(日历:日历,年:2019,月:12一天:3,小时:14分钟:39)如果让日期= calendar.date(来自:组件){打印(DateFormatter.localizedString(从日期,dateStyle:.medium,timeStyle:.medium))}
那会输出
2019年12月3日下午2:39:00
How do I create a date object in swift 4 that isn't the current date? For example December 3, 2019 @ 2:35PM. Then, how Do I write that object to a document in a firestore database as a timestamp?
You can create a DateFormatter object to convert native Date objects back and forth to strings and specify your dates as strings, but I don't recommend that.
Take a look at the Calendar
class and the DateComponents
class. The Calendar
function with the signature
func date(from components: DateComponents) -> Date?
lets you use a DateComponents
object to create a date.
So you might use code like this:
let calendar = Calendar.current
let components = DateComponents(
calendar: calendar,
year: 2019,
month: 12,
day: 3,
hour: 14,
minute: 39)
if let date = calendar.date(from: components) {
print(DateFormatter.localizedString(
from: date,
dateStyle: .medium,
timeStyle: .medium))
}
That would output
Dec 3, 2019 at 2:39:00 PM
这篇关于使用时间戳记功能将特定日期和时间保存到Firestore数据库-Swift 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!