【问题标题】:Subtracting two dates gives error "The operator - is undefined for the argument type(s) java.util.Date, java.util.Date" [duplicate]减去两个日期会给出错误“运算符 - 未定义参数类型 java.util.Date、java.util.Date” [重复]
【发布时间】:2014-07-22 12:53:44
【问题描述】:

在下面的代码中

  1. 关于从 date 中减去 date 给出此错误 "The operator - is undefined for the argument type(s) java.util.Date, java.util.Date"
  2. 变量currentDateString;为什么我不能将它保存在像这样的 Date 变量中
    Date currentDate = ddmmyy.format(new Date());.format 函数是否返回 String

    public class AgeCalculator {
    
      public static SimpleDateFormat ddmmyy=new SimpleDateFormat("dd/mm/yyyy");
    
    public static void main(String[] args) throws Exception {
    String dob = "05/01/1993";
    Date mod_date =  ddmmyy.parse(dob);
    String currentDate = ddmmyy.format(new Date());
    Date mod_currentDate = ddmmyy.parse(currentDate);
    int days = mod_currentDate-mod_date;
    
     }
    
    
    }
    

【问题讨论】:

  • here
  • 我应该在这里看什么,这并不能回答我的问题...

标签: java date


【解决方案1】:

首先将dd/mm/yyyy 更改为dd/MM/yyyymm-分钟为小时和MM-月份为一年

SimpleDateFormat ddmmyy=new SimpleDateFormat("dd/MM/yyyy");
String dob = "21/07/2014";
Date mod_date =  ddmmyy.parse(dob);
String currentDate = ddmmyy.format(new Date());
Date mod_currentDate = ddmmyy.parse(currentDate);

它将以毫秒为单位提供它们之间的差异,其类型为long

long differenceInMillis = mod_currentDate.getTime()-mod_date.getTime();

最后从毫秒获取天数

int days = (int) (differenceInMillis / (1000*60*60*24));
System.out.println(days);

【讨论】:

    【解决方案2】:

    也看看这里; Java, Calculate the number of days between two dates
    您的 mod_currentDate 返回 1 月 22 日而不是 7 月,因为您使用 mm 而不是 MM。

    public class AgeCalculator  {
         public static SimpleDateFormat ddmmyy=new SimpleDateFormat("dd/MM/yyyy");
    
          public static void main(String[] args) throws Exception {
          String dob = "05/01/1993";
          Date mod_date =  ddmmyy.parse(dob);
          Date currentDate = new Date();
          int days = daysBetween(mod_date,currentDate);
          System.out.println("Get the amount of days between " + mod_date + " and " + currentDate);
          System.out.println("Days= "+ days); 
           }
    
          public static int daysBetween(Date d1, Date d2){
            return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
        }
    }
    

    输出是:

    Get the amount of days between Tue Jan 05 00:00:00 CET 1993 and Tue Jul 22 16:19:02 CEST 2014
    Days= 7868
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 2018-05-25
      • 1970-01-01
      • 2018-03-20
      相关资源
      最近更新 更多