在下面的代码中
"The operator - is undefined for the argument type(s) java.util.Date, java.util.Date"
变量 currentDate 是String
;为什么我无法将其保存在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;
}
}
答案 0 :(得分:1)
首先将dd/mm/yyyy
改为dd/MM/yyyy
作为mm
- 以小时为单位的分钟和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);
答案 1 :(得分:0)
另外看看这里; 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