所以我从MySQL数据库获取时间戳,格式如下:2014-12-09 16:46:26
我想在将该日期应用于TextView之前 - 检查日期是今天还是昨天。 基本上就像:
if(timestamp == today){
TextView = "Today";
}
else if(timestamp == yesterday){
TextView = "Yesterday";
}
else{
TextView = FormatTimeStamp(DD/MM/YY hh:mm);
}
我写的是这段代码:
String dats = timestamp; //2014-12-09 16:46:26
String[] datsdt = dats.split("\\s+");
String[] dateSplit = datsdt[0].split("\\-");
String[] timeSplit = datsdt[1].split("\\:");
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH);
int day = Calendar.getInstance().get(Calendar.DATE);
然后将拆分日期部分与当前年月和日进行比较,但这似乎太长了,我确信这样做的方法不对。
那我该怎么做?
答案 0 :(得分:2)
使用SimpleDateFormat解析日期和日历以比较日期。:
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
Date date = sdf.parse("2014-12-09 16:46:26");
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DAY_OF_MONTH, -1);
yesterday.set(Calendar.HOUR_OF_DAY,0);
yesterday.set(Calendar.MINUTE,0);
yesterday.set(Calendar.SECOND,0);
yesterday.set(Calendar.MILLISECOND,0);
if (c.getTime().equals(new Date())){
//TODAY
} else if (c.equals(yesterday)) {
//yesterday
} else {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy hh:mm");
TextView = sdf1.format(date);
}