yambo
yambo

Reputation: 1817

Save specific date and times to Firestore database using the timestamp feature - Swift 4

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?

Upvotes: 1

Views: 2552

Answers (2)

snake_plissken
snake_plissken

Reputation: 129

if your dates are in string format like 2019/12/03 14:35

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
let date = dateFormatter.date(from: "2019/12/03 14:35")

you can send date object to firestore like that

let data:[String: Any] = ["notCurrentDate":date]

let db = Firestore.firestore()

db.collection("data").document("document").setData(data) { err in
  if let err = err {
      print("Error writing document: \(err)")
  } else {
      print("Document successfully written!")
  }
}

Upvotes: 0

Duncan C
Duncan C

Reputation: 131418

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

Upvotes: 1

Related Questions