我正在尝试创建一个以两个日期作为参数的程序,并返回日期是否在当前周,但我对isDateInCurrentWeek
的调用存在问题。当我尝试编译程序时,收到错误说
requestHoliday.java:16: isDateInCurrentWeek(java.util.GregorianCalendar) in requestHoliday cannot be applied to (java.util.Calendar)
if (isDateInCurrentWeek(startDate) && isDateInCurrentWeek(endDate));
import java.util.*;
import java.text.*;
public class hols {
public static void main( String[] args ) {
DateFormat df = new SimpleDateFormat("dd MM yyyy");
Date start = df.parse(args[0]);
Date end = df.parse(args[1]);
Calendar startDate = new GregorianCalendar();
Calendar endDate = new GregorianCalendar();
startDate.setTime(start);
endDate.setTime(end);
if( isDateInCurrentWeek( startDate ) && isDateInCurrentWeek( endDate ));
System.out.println( "Date is in current week!" );
}
public static boolean isDateInCurrentWeek(GregorianCalendar date) {
Calendar currentCalendar = GregorianCalendar.getInstance();
int week = currentCalendar.get(Calendar.WEEK_OF_YEAR);
int year = currentCalendar.get(Calendar.YEAR);
Calendar targetCalendar = GregorianCalendar.getInstance();
targetCalendar = date;
int targetWeek = targetCalendar.get(Calendar.WEEK_OF_YEAR);
int targetYear = targetCalendar.get(Calendar.YEAR);
return week == targetWeek && year == targetYear;
}
}
不太确定问题是什么,因为该方法将Gregoriancalendar作为输入,并且两个日期是格里高利历日历格式。有人知道吗?
答案 0 :(得分:2)
;
末尾有if
,请将其删除...
阳历是一个日历,而不是相反。 如果抽象和通用方法适合您的需要,请将签名更改为使用日历。如果可能,最好使用合同而不是What does it mean to "program to an interface"?中解释的实现(感谢Luiggi)。
hols id不是good class name。 Hols可能会更好......
此代码效果很好:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Hols {
public static void main( String[] args ) throws ParseException {
DateFormat df = new SimpleDateFormat("dd MM yyyy");
Date start = df.parse( args[0] );
Date end = df.parse( args[1] );
Calendar startDate = new GregorianCalendar();
Calendar endDate = new GregorianCalendar();
startDate.setTime(start);
endDate.setTime(end);
if( isDateInCurrentWeek( startDate ) && isDateInCurrentWeek( endDate ))
System.out.println( "Date is in current week!" );
else
System.out.println( "Date is NOT in current week!" );
}
public static boolean isDateInCurrentWeek( Calendar date ) {
Calendar currentCalendar = Calendar.getInstance();
int week = currentCalendar.get(Calendar.WEEK_OF_YEAR);
int year = currentCalendar.get(Calendar.YEAR);
Calendar targetCalendar = Calendar.getInstance();
targetCalendar = date;
int targetWeek = targetCalendar.get(Calendar.WEEK_OF_YEAR);
int targetYear = targetCalendar.get(Calendar.YEAR);
return week == targetWeek && year == targetYear;
}
}
答案 1 :(得分:1)
当您致电isDateInCurrentWeek
时,您传入的变量的类型为Calendar
。将它们声明为GregorianCalendar
。
如果您不需要任何GregorianCalendar
具体内容,请在isDateInCurrentWeek
更改方法签名以接受Calendar
。