比较公历日期值
问题描述:
我试图设置一个程序的一部分,允许一个人查看基于交易日期的账户交易。用户输入月和日来查看交易,并将其与连接到给定交易的日期进行比较。我有难以编写确定的代码行,如果日期等于比较公历日期值
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;
}
}
}
}
答
为原始值,您可以只使用==
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year
答
只需使用:
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH) == month
答
如果所有XYZ.getTransDate()
回报日历,然后XYZ.getTransDate().get(SOMETHING)
返回原始int
。基元没有comapreTo方法,只要使用==
所以不是XYZ.getTransDate().get(MONTH).compareTo(month) == 0
使用 XYZ.getTransDate().get(MONTH) == month
答
这应该工作:
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更好: