patternjavaMinor
Describing a date interval as text
Viewed 0 times
textintervaldatedescribing
Problem
public String getDatePeriodtext(boolean userCanJoinAndLeave, Date startDate, Date endDate) {
String text;
if (!userCanJoinAndLeave) {
text = getText(getLocale(), "no");
} else if (startDate == null && endDate == null) {
text = getText(getLocale(), "continuous");
} else if (startDate == null && endDate != null) {
text = getText(getLocale(), "to")
+ " "
+ formatDate(endDate);
} else if (endDate == null) {
text = getText(getLocale(), "from")
+ " "
+ formatDate(startDate);
} else {
text = formatDate(startDate)
+ " "
+ getText(getLocale(), "to")
+ " "
+ formatDate(endDate);
}
return text;
}Some scenarios:
userCanJoinAndLeave = false==> No
startDate = nullandendDate= null ==> Continuous
startDate = 2016-10-31andendDate = null==> from 2016-10-31
startDate = nullandendDate = 2016-11-01==> to 2016-11-01
startDate = 2016-10-31andendDate = 2016-11-01==> 2016-10-31 to 2016-11-01
Solution
I am not sure if you like this one better but I personally prefer returning directly (and therefore omitting the
else-clauses). I do not know if there was a better way.public String getDatePeriodtext(boolean userCanJoinAndLeave, Date startDate, Date endDate) {
if (!userCanJoinAndLeave)
return getText(getLocale(), "no");
if (startDate == null && endDate == null)
return getText(getLocale(), "continuous");
if (startDate == null && endDate != null)
return getText(getLocale(), "to")
+ " "
+ formatDate(endDate);
if (endDate == null)
return getText(getLocale(), "from")
+ " "
+ formatDate(startDate);
return formatDate(startDate);
+ " "
+ getText(getLocale(), "to")
+ " "
+ formatDate(endDate);
}Code Snippets
public String getDatePeriodtext(boolean userCanJoinAndLeave, Date startDate, Date endDate) {
if (!userCanJoinAndLeave)
return getText(getLocale(), "no");
if (startDate == null && endDate == null)
return getText(getLocale(), "continuous");
if (startDate == null && endDate != null)
return getText(getLocale(), "to")
+ " "
+ formatDate(endDate);
if (endDate == null)
return getText(getLocale(), "from")
+ " "
+ formatDate(startDate);
return formatDate(startDate);
+ " "
+ getText(getLocale(), "to")
+ " "
+ formatDate(endDate);
}Context
StackExchange Code Review Q#145728, answer score: 3
Revisions (0)
No revisions yet.