Home > Enterprise >  lastSignInTimestamp is bigger than the current timestamp in Firebase
lastSignInTimestamp is bigger than the current timestamp in Firebase

Time:12-09

I just implemented Firebase auth. After I sign-up, I want to know much time my users spend in my app. If I try:

val t1 = Date(auth.currentUser?.metadata?.lastSignInTimestamp).time
val t2 = Date().time
val result = t2 - t1
print(result) //prints (-3 seconds)

Right after createUserWithEmailAndPassword completes, I get a negative value. How can the current timestamp be before the timestamp of an authentication that is completed few seconds earlier? How to solve this?

CodePudding user response:

The timestamps in the user's metadata are generated on the Firebase Authentication server, while Date().time generates a timestamp in the place where your code executes. Since these timestamps comes from different machines, there's a chance that there is a (positive or negative) offset between the clocks on these two machines.

If you want to measure this so-called skew, you can capture the local timestamp (Date().time) when the user signs in, and compare that with the server timestamp (auth.currentUser?.metadata?.lastSignInTimestamp). Since the offset is likely fixed, you can then continue to use this offset in the rest of your application.

  • Related