给你一个临近的日期,如何计算是今天,昨天还是明天,后天呢?
我们可以把两个时间转成时间戳,然后计算,除以每天的时间长度,得到天数。
根据这个天数结合正负,判断是哪一天。
private int getDayDx(Date date) {
Calendar today = Calendar.getInstance();
today.setTime(new Date());
Calendar targetDate = Calendar.getInstance();
targetDate.setTime(date);
//置整计算
today.set(Calendar.HOUR, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
targetDate.set(Calendar.HOUR, 0);
targetDate.set(Calendar.MINUTE, 0);
targetDate.set(Calendar.SECOND, 0);
targetDate.set(Calendar.MILLISECOND, 0);
//老的时间减去今天的时间
long dT = targetDate.getTimeInMillis() - today.getTimeInMillis();
int dx = (int) (dT * 1.0f / (24 * 60 * 60 * 1000));
// -2:前天 -1:昨天 0:今天 1:明天 2:后天
if (dx >= -2 && dx <= 2) {
return dx;
} else {
return dx;
}
}
有了这个dx值以后,进行换算
private void handTopDayText(int dx) {
//明天
if (dx== 1) {
topDayTextTV.setText(R.string.tomorrow_text);
} else if (dx== 2) {
topDayTextTV.setText(R.string.the_day_after_tomorrow_text);
} else if (dx==-1) {
topDayTextTV.setText(R.string.the_day_before_yesterday);
} else if (dx== -2) {
topDayTextTV.setText(R.string.yesterday);
} else if (dx== 0) {
topDayTextTV.setText(R.string.today_text);
}else if(dx>0){
//XXX天后
}else if(dx<0){
//XXX天前
}
}
这样子,我们就可以计算出时间了,一般来说做天气呀,或者某些动态的格式化就用得上了。