'How to properly add time to Firestore & compare it to a future timestamp to determine a subscription expiry date swift

What is the proper way to save time to Firestore & how do I get back the values to compare them & determine if a subscription is expired?

I am currently using:

  1. Apple's date & components to save expiry date
  2. FieldValue.serverTimestamp() to save purchased date &
let now = Date()
let components = DateComponents(day:45)
var futureTimeStamp: TimeInterval = 0.0
        
if let future = calendar.date(byAdding: components, to: now, wrappingComponents: false) {
       print(DateFormatter.localizedString(from: future, dateStyle: .medium, timeStyle: .medium))
            
       futureTimeStamp = future.timeIntervalSince1970
      
} else {
       print("Can't create date")
}

self.db.collection("users/subscriptions").document("\(subscriptionDoc)").setData([
    "product" : "Grade1",
    "dateExpiry" : futureTimeStamp,
    "datePurchased" : FieldValue.serverTimestamp(),
    "userId" : userId
])

The Firebase time is represented as seconds and fractions of seconds at nanosecond in UTC Epoch time. (ex. Jun 3, 2022 at 12:59:43 PM is 1654275583.406064)

In Firestore I see:

  1. dateExpiry as a number &
  2. datePurchased as a timestamp:

enter image description here

However, when I get the document I return the following

Optional([ "dateExpiry": 1654275583.406064, "datePurchased": ])

As you can see the datePurchased from serverTimeStamp() is null even though there is a date in the document on Firestore.



Solution 1:[1]

The Calendar class has lots of methods to do "calendrical calculations" on dates.

I suggest using the function date(byAdding:to:wrappingComponents:):

import Foundation

let calendar = Calendar.current
let now = Date()
let components = DateComponents(day:45)
if let future = calendar.date(byAdding: components, to: now, wrappingComponents: false) {
    print(DateFormatter.localizedString(from: future, dateStyle: .medium, timeStyle: .medium))
} else {
    print("Can't create date")
}

That outputs the following:

May 21, 2022 at 6:36:32 AM

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 Duncan C