1

I want to display the user's last sign-in date in Kotlin but it always returns today's day.

val user :FirebaseUser = FirebaseAuth().getInstance().currentUser!!
val timeStamp : Timestamp = Timestamp(user.metadata?.lastSignInTimestamp!!)
val date = Date(timeStamp.time)
Toast.make(this, date.toString() ,Toast.LENGTH_SHORT).show()
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

I want to display the user's last sign-in date in Kotlin

To display the user's last sign-in date in a Kotlin "style", please use the following lines of code:

FirebaseAuth.getInstance().currentUser?.metadata?.apply {
    val lastSignInDate = Date(lastSignInTimestamp)
    Toast.makeText(this, lastSignInDate.toString() ,Toast.LENGTH_SHORT).show()
}

The result will be a Toast message containing the String representation of the "lastSignInDate" object, which is an object of type Date. Let's suppose the user has signed in last time yesterday, the message might look similar to this:

Wed Mar 31 11:20:10 GMT+03:00 2021

If needed, you can also format the Date in a more readable way, as explained in the answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thanks for the answer but it still gives the today's date. For example, I have an account that last signed in the app 3 days ago. I want to display the date that user last signed in the app which is 3 days ago but the result is today's date. – Abdulsamet Kılınçarslan Apr 01 '21 at 10:33
  • Are you sure you are signed-in with the user credentials that last signed in the app 3 days ago? If you are signed-in with a user that has last signed-in the app today, the result will a message with today's date. – Alex Mamo Apr 01 '21 at 10:34
  • I tried different accounts that signed in different days but the result is still today's date. I'll work on it and check which part is wrong. Thank you very much for the answer. – Abdulsamet Kılınçarslan Apr 01 '21 at 10:43
  • 1
    You're very welcome. Try to check for sure which user are you using and the last sign-in date and keep me posted. – Alex Mamo Apr 01 '21 at 10:57
  • I tried different accounts but still I get today's date. Is it because the Firebase immediately updates the last sign-in date after I sign in the app ? – Abdulsamet Kılınçarslan Apr 01 '21 at 11:11
  • Yes indeed, Firebase immediately updates the last sign-in date after you sign-in. To see the desired behavior, sign-in a user, keep it that way till the next day (don't sign-out) and try the next day. Keep me posted. – Alex Mamo Apr 01 '21 at 11:21