'SwiftUI - Firebase - Save Date without time
hi everyone I have this structure that I use to save data on firebase ... As you can see I have a var reservation_date: Date field
Firebase obviously saves a date with the time but I would need only the date without the time to be saved how can I get this?
This is how I save me
struct Reservations: Identifiable, Codable {
@DocumentID var id: String?
var reservation_date: Date
var user: String
@ExplicitNull var userID: String?
var reservation_id: String
@FirebaseFirestoreSwift.ServerTimestamp var createdAt: Timestamp?
enum CodingKeys: String, CodingKey {
case id
case reservation_date
case user
case userID
case reservation_id
case createdAt
}
static let sample = Reservations(reservation_date: Date(), user: "", userID: "", reservation_id: "")
}
// MARK: - Firebase
extension ReservationViewModel {
func addReservation() {
guard let newDate = Calendar.current.date(bySettingHour: hour, minute: minute, second: 0, of: selectedDate) else {
print("Non è stato possibile creare una data di prenotazione valida")
return }
let dBPath = db.collection("Prenotazioni")
.document(newDate.formatted(.dateTime.year()))
.collection(newDate.formatted(.dateTime.month(.wide).locale(Locale(identifier: "it"))))
.document(newDate.formatted(.dateTime.day(.twoDigits)))
.collection("Ore \(newDate.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).locale(Locale(identifier: "it"))) + ":" + newDate.formatted(.dateTime.minute(.twoDigits)))")
do {
let _ = try dBPath.addDocument(from: reservation)
}
catch {
print(error)
}
}
}
Solution 1:[1]
If you're only interested in the date value then I would recommend using a string that conforms to the ISO 8601 standard, which in this particular case would just be yyyy-mm-dd (ex: "2022-02-13"). Swift has a ready-made ISO-8601 formatter exactly for this.
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate]
// From String to Date
let reservationDay = "2022-03-25" // save this in your database
if let date = formatter.date(from: reservationDay) {
print(date) // Swift Date object
}
// From Date to String
let reservationDate = Date()
let day = formatter.string(from: reservationDate)
print(day) // String "2022-02-13"
Be mindful of timezones, however, because the default is GMT and you will want to use GMT throughout the conversions (and then render the local timezone value) or the local timezone throughout the conversions (just don't mix them as you convert). To always deal in the local timezone you can set its property on the formatter:
formatter.timeZone = .current
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fake girlfriends |
