比较公历日期值

时间:2011-06-06 03:33:31

标签: java gregorian-calendar

我正在尝试设置一个程序的一部分,该程序允许一个人根据交易日期查看帐户的交易。用户输入月份日和年份以查看交易,并将其与连接到给定交易的日期进行比较。我很难编写确定日期是否相等的代码行

if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
                        if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
                            if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){

我收到的错误是“无法在基本类型int上调用compareTo(int)” 请参阅以下完整代码:

System.out.println("Enter the account number of the account that you want to view transactions for");
            number=keyboard.nextLong();
            System.out.println("Enter the month day and year of the date that the transactions were completed");
            int month=keyboard.nextInt()-1;
            int day=keyboard.nextInt();
            int year=keyboard.nextInt();
            found=false;
            try{
            for(int i=0;i<aBank.getAccounts().size();i++){
                if (aBank.getAccounts().get(i).getAccountNumber().compareTo(number)==0){
                    found=true;
                    System.out.println("Below is a list of transactions completed on "+month+ "/" +day+ "/" +year);
                    for (int j=0;j<aBank.getAccounts().get(i).getTransaction().size();j++){
                    if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
                        if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
                            if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){
                                aBank.getAccounts().get(i).getTransaction().get(j).toString();
                                break;
                            }
                        }

                    }

                }

4 个答案:

答案 0 :(得分:1)

对于原始值,您只需使用==

即可
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year

答案 1 :(得分:1)

只需使用:

aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH) == month

答案 2 :(得分:1)

如果所有XYZ.getTransDate()都返回日历,则为 XYZ.getTransDate().get(SOMETHING)返回原始 int 。基元没有comapreTo方法,只需使用==

所以不要使用XYZ.getTransDate().get(MONTH).compareTo(month) == 0 XYZ.getTransDate().get(MONTH) == month

答案 3 :(得分:0)

这应该有效:

Calendar transDate = aBank.getAccounts().get(i).getTransaction().get(j).getTransDate();
if (transDate.get(Calendar.YEAR) == year &&
    transDate.get(Calendar.MONTH) == month &&
    transDate.get(Calendar.DAY_OF_MONTH) == day) {

    // do something
}

如果您使用Apache Commons Lang之类的东西,那就更好了:

if (DateUtils.isSameDay(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate(),
                        Calendar.getInstance().set(year, month, day)) {
    ...
}