I have two screens where I show a message creation time and date. Initially, there was only one screen and I should always show time and show date differently depending on difference between today and the message creation day.
Here is my method:
private final static String TIME_TEMPLATE_TODAY = "HH:mm";
public static String getFormattedDate(Date msgDate, Date currentTime) {
long daysDiff = Utils.getDaysDiff(currentTime, msgDate);
String format;
if (currentTime.getYear() != msgDate.getYear()) {
format = "dd.MM.yyyy' at '" + TIME_TEMPLATE_TODAY;
} else if (daysDiff == 0) {
format = TIME_TEMPLATE_TODAY;
} else if (daysDiff == 1) {
format = "'yesterday at " + TIME_TEMPLATE_TODAY;
} else if (daysDiff > 1) {
format = "dd.MM' at '" + TIME_TEMPLATE_TODAY;
} else {
format = "dd.MM.yyyy";
Timber.e("Unexpected time diff: %d", daysDiff);
}
return new SimpleDateFormat(format, Locale.CANADA).format(msgDate);
}
And now I should add cases for the second screen: show time only if it is today, otherwise, show only date (or "yesterday") without time.
I came up with solution below:
public static String getFormattedDate(Date msgDate, Date currentTime, boolean alwaysShowTime) {
long daysDiff = Utils.getDaysDiff(currentTime, msgDate);
StringBuilder format = new StringBuilder();
// Add date representation
if (currentTime.getYear() != msgDate.getYear()) {
format.append("dd.MM.yyyy'");
} else if (daysDiff == 1) {
format.append("'вчера'");
} else if (daysDiff > 1) {
format.append("dd.MM");
} else {
format.append("dd.MM.yyyy");
Timber.e("Unexpected time diff: %d", daysDiff);
}
// Add time
if (daysDiff == 0) {
format.append(TIME_TEMPLATE_TODAY);
} else if (alwaysShowTime) {
format.append("' at '")
.append(TIME_TEMPLATE_TODAY);
}
return new SimpleDateFormat(format.toString(), Locale.CANADA).format(msgDate);
}
Disadvantages that I see are:
I changed method contract (but it used in 1-2 places, so it is not a big deal in this case)
I need to always pass this third parameter to the method. I can solve both points creating another method with a previous contract and pass some default value for
alwaysShowTime
If some third option appears, I would have to change the contract again, changing
Boolean
toenum
, for example.
What problems or possible optimizations do you see here? Should I just create a new method and extract some common logic to a private method instead changing existing one?