Home > OS >  How can I read date ( timestamp ) from Cloud-Firestore?
How can I read date ( timestamp ) from Cloud-Firestore?

Time:08-03

I have a ProfileFragment where I want to show the user's profile. I also added the birth date in Firestore and now I want to display it for the current user on his profile so, how can I do that? Do I have to convert it to a string or what should I do ? I tried to make it a string with .toString() but it isn't displayed.If I let it like that or make it a Date it will show me an error when I try to "setText" to the TextView variable.

TVbirthdate = getActivity().findViewById(R.id.birthdateinfo);
Timestamp birthResult = task.getResult().getTimestamp("Birth Date");
TVbirthdate.setText(birthResult.toDate());

Thanks!

CodePudding user response:

You have to convert the timestamp to the actual date format first before using it on the setText() method. See sample converter function below:

private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time);
    String date = DateFormat.format("dd-MM-yyyy", cal).toString();
    return date;
}

After converting, you can now set this date using the setText() method. See sample code below:

// birthResult here is the Timestamp object from Firestore
TVbirthdate.setText(getDate(birthResult));

If the above code is not possible for your use-case, you can also use SimpleDateFormat. See sample implementation below:

Date dataDate = birthResult.toDate();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TVbirthdate.setText(sdf.format(dataDate));
  • Related