在 Java 静态方法中,使用“today”和“yesterday”字符串简化日期对象的替换
我有以下方法,如果没有别的,我想缩短或更快。欢迎大家提出意见:
Bellow方法获取一个日期对象,对其进行格式化(“EEE hh:mma MMM d,yyyy”),然后确定日期是今天还是昨天,如果是,则返回“(昨天|今天)hh:mma“格式的字符串。
public static String formatToYesterdayOrToday(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("EEE hh:mma MMM d, yyyy");
Date in = null;
try {
in = sdf.parse(date);
} catch (ParseException e) {
log.debug("Date parsing error:", e);
}
Calendar x = Calendar.getInstance();
x.setTime(in);
String hour = Integer.toString(x.get(Calendar.HOUR));
String minute = Integer.toString(x.get(Calendar.MINUTE));
String pm_am = x.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM";
x.set(Calendar.HOUR, 0);
x.set(Calendar.HOUR_OF_DAY, 0);
x.set(Calendar.MINUTE, 0);
x.set(Calendar.SECOND, 0);
x.set(Calendar.MILLISECOND, 0);
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR, 0);
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
Calendar yesterday = Calendar.getInstance();
yesterday.set(Calendar.HOUR, 0);
yesterday.set(Calendar.HOUR_OF_DAY, 0);
yesterday.set(Calendar.MINUTE, 0);
yesterday.set(Calendar.SECOND, 0);
yesterday.set(Calendar.MILLISECOND, 0);
yesterday.add(Calendar.DATE, -1);
if (x.compareTo(today) == 0) {
return "Today " + hour + ":" + minute + pm_am;
}
if (x.compareTo(yesterday) == 0) {
return "Yesterday " + hour + ":" + minute + pm_am;
}
return date;
}