I followed different answers from here and here
I'm just getting started learning Cloud Tasks from here. In that blog post Doug says "What I want is for expirationAtSeconds to be the time of expiration expressed in epoch seconds".
I want the Task to delete the post when that time is set. In my iOS app I create a post that expires at a specific time:
let timeStamp = Date().timeIntervalSince1970
let postDate: Date = Date(timeIntervalSince1970: timeStamp)
var expirationDate: Date? = Calendar.current.date(byAdding: .hour, value: +24, to: postDate)
guard let exp = expirationDate else { return }
let expiresAt = exp.timeIntervalSince1970
dict.updateValue(expiresAt, forKey: "expiresAt")
dict.updateValue(timeStamp, forKey: "postDate")
// other values ...
ref.updateChildValues(dict)
which gives me a database value like:
posts
some_post_Id
-"expiresAt": 1632627680.340107
// other values ...
In my cloud function I want the expiresAt date which is a Double expressed in Epoch seconds. I'm not sure if I should use expDate1, expDate2, expDate3, or expDate4:
exports.onCreatePost = functions.database.ref('/posts/{postId}').onCreate((snapshot, context) => {
const post = snapshot.data();
const expiresAt = snapshot.child("expiresAt").val();
const expirationDate = expiresAt.valueOf(); // 1632627680.340107
var expDate1 = DateTime.fromMillisecondsSinceEpoch(expirationDate * 1000)
var expDate2 = DateTime.fromMicrosecondsSinceEpoch(expirationDate * 1000000)
var expDate3 = DateTime.fromMicrosecondsSinceEpoch(expirationDate.microsecondsSinceEpoch)
var expDate4 = expirationDate.toDate()
const expirationAtSeconds = either expDate1, expDate2, expDate3, or expDate4
// continue on with the rest of the code ...
});
From my question none of the above DateTime methods worked for me because I kept getting an error TypeError: Cannot read property 'DateTime' of undefined.
I had to use new Date(expirationDate * 1000) and I got the conversion to epoch seconds from here
Code:
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();
exports.onCreatePost = functions.database.ref('/posts/{postId}').onCreate((snapshot, context) => {
const post = snapshot.data();
const expiresAt = snapshot.child("expiresAt").val();
const expirationDate = expiresAt.valueOf(); // 1632627680.340107
const expDate = new Date(expirationDate * 1000); // <--------Here
const expirationAtSeconds = expDate.getTime()/1000.0; // <-------- this will be epoch seconds conversion
console.log("expDate: " + expDate + " | expirationAtSeconds:" + expirationAtSeconds);
// continue on with the rest of the code ...
});