Difference between 2 dates ( timestamps ) Android Studio and Cloud Firestore

Viewed 26

I want to make the difference between the current date and the users' birth date in order to display how many days remained until their birthday. I have a recyclerView in which I put the users and an Adapter for this recyclerView but for some reason, the days aren't computed as I want.

The birth date is stored in Firestore as a timestamp : enter image description here

In CalendarAdapter.java :

    public CalendarAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemcalendar, parent, false);
        CalendarAdapter.ViewHolder myViewHolder = new CalendarAdapter.ViewHolder(v);

        return myViewHolder;
    }
    private String getStringFromDate(Timestamp time) {
        java.util.Date dateFromServer = time.toDate();
        String formatter = new SimpleDateFormat("dd/MM/yyyy").format(dateFromServer);
        return formatter;
    }

    private String calculateDays(Timestamp startdate, Timestamp enddate){
        SimpleDateFormat dates = new SimpleDateFormat("dd/MM/yyyy");
        Date date1 = startdate.toDate(); // current date
        Date date2 = enddate.toDate(); // friend's birthdate

        long difference = Math.abs(date2.getTime() - date1.getTime());
        long differenceDates = difference / 24;

        String dayDifference = Long.toString(differenceDates);

        return dayDifference;
    }

    @Override
    public void onBindViewHolder(@NonNull CalendarAdapter.ViewHolder holder, int position) {
        Friends friend = listofbirtdays.get(position);
        long currentdate = System.currentTimeMillis()/1000;
       // java.util.Date dateFromServer = currentdate.toDate();
        Date c = Calendar.getInstance().getTime();

        Log.d(TAG, "Current Date" + c);
        Timestamp ts = new Timestamp(c);
        SimpleDateFormat dates = new SimpleDateFormat("dd/MM/yyyy");
        
        
        holder.birthdayperson.setText(friend.friendname);
        holder.datebirth.setText(getStringFromDate(friend.friendBD));
        holder.noofdays.setText(calculateDays(ts, friend.friendBD));
    }

    @Override
    public int getItemCount() {
        return listofbirtdays.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        View rootview;
        TextView birthdayperson, datebirth, noofdays;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            rootview = itemView;

            birthdayperson = itemView.findViewById(R.id.birthdayperson);
            datebirth = itemView.findViewById(R.id.datebirth);
            noofdays = itemView.findViewById(R.id.noofdays);
        }
    }

So I repeat, I want to compute only the days until the next birthday, how can I do that? What am I doing wrong? My result is this meaning that there are 17 days left until May 9 which is wrong : enter image description here

1 Answers

Since you're using a Firestore Timestamp, then it's best to get the time out of those objects and make the difference, and then simply calculate the total number of days.

Since the birthday it's always a date in the past, then a relatively simple option that we have is to set the year to be the current year (2022), and then check if the date is before or after.

To achieve that, I will show you an example. Let's assume I am born on 1 June 2000. Besides that, let's assume you have a Firestore structure that looks like this:

Firestore-root
  |
  --- users (collection)
       |
       --- $uid
            |
            --- birthday: June 1, 2000 at 9:00:00 AM UTC+2
//                         

For calculating the number of days between today, and my birthday, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            Date birthday = task.getResult().getDate("birthday");
            Date now = new Date();
            birthday.setYear(now.getYear());
            long difference;
            int daysBetween;
            if (birthday.after(now)) {
                difference = birthday.getTime() - now.getTime();
                daysBetween = (int) (difference / (1000 * 60 * 60 * 24));
            } else {
                difference = now.getTime() - birthday.getTime();
                daysBetween = 365 - (int) (difference / (1000 * 60 * 60 * 24));
            }
            Log.d(TAG, "difference: " + daysBetween);
        }
    }
});

The result in the logcat will be:

254

If I set my birthday like this:

Firestore-root
  |
  --- users (collection)
       |
       --- $uid
            |
            --- birthday: December 1, 2000 at 9:00:00 AM UTC+2
//                         

The result in the logcat will be:

71

This is an example of reading a single document, but the exact same solution will work in the case of a query. Besides that, you can also use the exact same logic in your adapter class.

Related