在這裏我比較兩個日期後顯示消息上面的消息。如果我顯示每個項目的日期,它工作正常。但是當我試圖顯示Today
,Yesterday
和date
時,它總是隻顯示date
。這裏日期沒有錯,但是它的格式日期錯了。在RecyclerView適配器中顯示錯誤的日期
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss");
try {
Date current_itemDate = simpleDateFormat.parse(chatMessage.getDateTime());
DateFormat outputFormat = new SimpleDateFormat("hh:mm a");
Date date = simpleDateFormat.parse(chatMessage.getDateTime());
holder.timeTextView.setText(outputFormat.format(date));
long previousTs = 0;
if (position > 0) {
ChatMessage pm = chatMessages.get(position - 1);
previousTs = simpleDateFormat.parse(pm.getDateTime()).getTime();
}
setTimeTextVisibility(current_itemDate.getTime(), previousTs, holder.textViewTimePeriod,
holder.dividerTop);
} catch (ParseException e) {
e.printStackTrace();
}
我使用的邏輯,用於示出具有日期或天
TextView
在下面提及。請讓我知道如果我做錯了什麼。
private void setTimeTextVisibility(long now_tm, long msg_tm, TextView timeText, View dividerTop) {
Calendar now_calendar = Calendar.getInstance();
Calendar msg_calendar = Calendar.getInstance();
now_calendar.setTimeInMillis(now_tm);
msg_calendar.setTimeInMillis(msg_tm);
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);
if (msg_tm == 0) {
timeText.setVisibility(View.VISIBLE);
dividerTop.setVisibility(View.VISIBLE);
if (now_calendar.get(Calendar.DATE) == msg_calendar.get(Calendar.DATE)) {
timeText.setText("Today");
} else if (!sameDay) {
timeText.setText("Yesterday");
} else {
timeText.setText("" + new SimpleDateFormat("dd MMM, yyyy").format(new Date(now_tm)));
}
} else {
if (sameDay) {
timeText.setVisibility(View.GONE);
dividerTop.setVisibility(View.GONE);
timeText.setText("");
} else {
timeText.setVisibility(View.VISIBLE);
dividerTop.setVisibility(View.VISIBLE);
timeText.setText("Today");
}
}
}
是的,它是一個很好的方法,我也使用'.before'函數改進了我的代碼片段。 –