I have following method that I would like to make shorter or faster if nothing else. Please all comments are welcome:
Bellow method takes a date object, formates it ("EEE hh:mma MMM d, yyyy") and then figures out if the date is today or yesterday and than, if it is, it returns "(Yesterday | Today) hh:mma" formated string.
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;
}
I know I am late to this party. But I have shortest solution for this problem. If you want to show "Today" or "Yesterday" based on the Date then you just need to use this
here variable date is the Date object.
This is extended versino of Balusc's implementation.
Try this, i implemented it using joda-datatime2.2.jar and SimpleDateFormat
Simple cases to use and test the Util class:
Here's how you could improve it with the standard API:
Here's how you could do it with Jodatime: