Java判断指定日期是否在今天昨天一周内
根据字符串类型的时间格式(2021-03-15 09:28:46)转化成 :今天、昨天、一周内、更早
public class DateUtils {
public static void main(String[] args) {
getDateDescribe("2021-03-14 09:28:46");
}
/**
* 根据字符串类型的时间格式(2021-03-15 09:28:46)转化成 :
* 今天、昨天、一周内、更早
*/
public static String getDateDescribe(String originDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = sdf.parse(originDate);
long timeMillis = System.currentTimeMillis();
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(timeMillis));
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date weekDate = sdf.parse(sdf.format(calendar.getTime()));
Date todayDate = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
Date yesterdayDate = sdf.parse(sdf.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24)));
if (date1.compareTo(todayDate) == 0){
System.out.println("今天");
return "今天";
}else if (date1.compareTo(yesterdayDate) == 0){
System.out.println("昨天");
return "昨天";
}else if (date1.compareTo(weekDate) > 0){
System.out.println("一周内");
return "一周内";
}else {
System.out.println("更早");
return "更早";
}
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}