我想要发生什么 - 如果日期(从参数给出)等于该月的最后一天,我希望成本增加10%。即如果dayOfTravel =该月的最后一天
public static double ReturnJourneyCost(int journeyID, int dayOfTravel, int monthOfTravel, int yearOfTravel){
Cost = Double.parseDouble(XMLLoad.load(journeyID, 3));
return Cost;
}
答案 0 :(得分:5)
使用旧的JDK-stuff,答案可能如下:
public static boolean isLastDayOfMonth(int year, int month, int day) {
GregorianCalendar gcal = new GregorianCalendar(year, month - 1, day);
gcal.add(Calendar.DATE, 1);
return (gcal.get(Calendar.DAY_OF_MONTH) == 1);
}
在Java 8中(更好的是因为它避免了对系统时区的任何隐式引用):
public static boolean isLastDayOfMonth(int year, int month, int day) {
LocalDate date = LocalDate.of(year, month, day);
return date.lengthOfMonth() == day;
}
答案 1 :(得分:4)
使用GregorianCalendar.getActualMaximum()
之类的东西可以解决这个问题:
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.YEAR, yearOfTravel);
calendar.set(Calendar.MONTH, monthOfTravel); // warning: 0-based!
calendar.set(Calendar.DAY_OF_MONTH, dayOfTravel);
int daysInThisMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
if (daysInThisMonth == dayOfTravel)
{
// increase cost by 10%
}
答案 2 :(得分:0)
你需要写一些自定义代码......
public boolean isLastDay(Date date) {
Calendar now = Calendar.getInstance();
now.setTime(date);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, 1);
return c.get(Calendar.MONTH) != now.get(Calendar.MONTH);
}
答案 3 :(得分:0)
你可以试试这个:
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.MONTH) == monthOfTravel &&
&& calendar.ger(Calendar.YEAR) == yearOfTravel && calendar.getActualMaximum(Calendar.DAY_OF_MONTH) == dayOfTravel) {
//...
}