Skip to content Skip to sidebar Skip to footer

Displaying Wrong Date In Recyclerview Adapter

Here I'm showing date above messages after comparison two dates. If I show dates with each item it works fine. but when I'm trying to show Today, Yesterday and date its always show

Solution 1:

Try to convert your date into Millis and then compare using these <,>,<=,>=,==,!= operators or check this link

.after is used to comparing the dates

Solution 2:

Here I want to show other developers how we can display the day before the messages like whatsapp application does.

privatevoidsetTimeTextVisibility(long now_tm, long msg_tm, TextView timeText, View dividerTop) {
    Date nowDate = new Date();
    nowDate.setTime(now_tm);
    Date msgDate = new Date();
    msgDate.setTime(msg_tm);
    Calendar now_calendar = Calendar.getInstance();
    now_calendar.setTimeInMillis(now_tm);
    Calendar now = Calendar.getInstance();
    Calendar msg_calendar = Calendar.getInstance();
    msg_calendar.setTimeInMillis(msg_tm);
    if (msg_tm == 0) {
        timeText.setVisibility(View.VISIBLE);
        dividerTop.setVisibility(View.VISIBLE);
        if (DateUtils.isToday(now_calendar.getTimeInMillis())) {
            timeText.setText("Today");
        } elseif (now.get(Calendar.DATE) - now_calendar.get(Calendar.DATE) == 1) {
            timeText.setText("Yesterday");
        } else
            timeText.setText("" + new SimpleDateFormat("dd MMM, yyyy").format(new Date(now_tm)));
    } else {
        if (msgDate.before(nowDate)) {

            boolean sameDay = now_calendar.get(Calendar.YEAR) == msg_calendar.get(Calendar.YEAR) &&
                    now_calendar.get(Calendar.MONTH) == msg_calendar.get(Calendar.MONTH)
                    && now_calendar.get(Calendar.DAY_OF_MONTH) == msg_calendar.get(Calendar.DAY_OF_MONTH);
            Log.e("YESTERDAY", (now.get(Calendar.DATE) - msg_calendar.get(Calendar.DATE) == 1) + "");
            if (sameDay) {
                timeText.setVisibility(View.GONE);
                dividerTop.setVisibility(View.GONE);
                timeText.setText("");
            } else {
                timeText.setVisibility(View.VISIBLE);
                dividerTop.setVisibility(View.VISIBLE);
                if (DateUtils.isToday(now_calendar.getTimeInMillis())) {
                    timeText.setText("Today");
                } elseif (now.get(Calendar.DATE) - now_calendar.get(Calendar.DATE) == 1) {
                    timeText.setText("Yesterday");
                } else {
                    timeText.setText("" + new SimpleDateFormat("dd MMM, yyyy").format(new Date(now_tm)));
                }
            }
        } else {
            timeText.setVisibility(View.GONE);
            dividerTop.setVisibility(View.GONE);
            timeText.setText("");
        }
    }


}

Post a Comment for "Displaying Wrong Date In Recyclerview Adapter"