有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java8中日期对象的after函数问题

日期对象中的after()函数有问题。 这是我正在尝试运行的函数:

    private void setDebitDateInAction(Action action) {

    // The day the credit card debit is made
    int dD = action.getMethodPayment().getDebitDate();
    System.out.println("1) The debit day is every "+dD+" in  month.");

    //The date the purchase was made
    Date actionDate = action.getActionDate();
    System.out.println( "2) The purchase was in "+ actionDate.toString() );

    //The date the purchase will be charged
    Date debitDate = actionDate;
    System.out.println("3) Currently the debit date is "+debitDate.toString()  ); 

    //0 means immediate charge
    if(dD == 0) {
        //Leave the billing date as the purchase date.
    }else {
        // Change the day of the billing date
        debitDate.setDate(dD);
        System.out.println("4) The day of the debit date has changed to "+dD+" and new the debit date is " +debitDate.toString()  ); 
        if(actionDate.after(debitDate)) {
            debitDate.setMonth(debitDate.getMonth()+1);
            System.out.println("5) The month of the debit date has changed to "+debitDate.getMonth() + 1 +" and new the debit date is " +debitDate.toString()  ); 
        }
    }
    action.setDebitDate(debitDate);
    System.out.println("6) ActionDebit is set to" +debitDate.toString()  ); 
}

这是我在控制台中输入Action函数后得到的结果,actionDate为2019年7月15日,methodPayment的日期(出于信用目的)为10日

1) The debit day is every 10 in  month.
2) The purchase was in Mon Jul 15 03:00:00 IDT 2019
3) Currently the debit date is Mon Jul 15 03:00:00 IDT 2019
4) The day of the debit date has changed to 10 and now the debit date is Wed Jul 10 03:00:00 IDT 2019
6) ActionDebit is set toWed Jul 10 03:00:00 IDT 2019

我希望计费日期为2019年8月10日,但不成功。 由于某种原因,他没有意识到购买日期在账单日期之后


共 (2) 个答案

  1. # 1 楼答案

    将日期设置为相同的值:

    Date actionDate = action.getActionDate();
    Date debitDate = actionDate;
    

    当你现在检查

    if(actionDate.after(debitDate))
    

    你会得到“假”——因为日期是相等的。您需要以不同的方式设置日期

    您正在调用借记日期,但这似乎不是正确的日期。。。检查这个

    action.getMethodPayment().getDebitDate()
    
  2. # 2 楼答案

    因此,有两种(以下)情况:

    1. CompareTo()-如果您使用的是正确的'debitDate:

    这是因为actionDatedebitDate是相同的,因此if(actionDate.after(debitDate))在两个日期相同的情况下总是返回false

    您应该使用compareTo()

    代码应该如下所示:

    if(actionDate.compareTo(debitDate) >=0) {
    debitDate.setMonth(debitDate.getMonth()+1);
                System.out.println("5) The month of the debit date has changed to "+debitDate.getMonth() + 1 +" and new the debit date is " +debitDate.
    }
    
    1. 您使用了错误的debitDate: 您应该设置正确的debitDate,代码应该如下所示:

      //购买的收费日期

      日期debitDate=操作。getMethodPayment()。getDebitDate()

    我希望这能解决你的问题