When I code like this I get no error :-
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class DateDifference{
public static void main(String[] main){
String str = "20121401092958";
/* TimeUnit spanInDays = */getDateDiff(str);
//System.out.println(spanInDays);
}
public static void getDateDiff(String str ){
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date currentDate = new Date();
Date givenDate = null;
Date d2 = null;
try{
givenDate = dateFormat.parse(str);
long diff = currentDate.getTime() - givenDate.getTime();
System.out.println("Days "+ TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
}catch(Exception e){
e.printStackTrace();
}
}
}
but when I code it like this :-
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class DateDifference{
public static void main(String[] main){
String str = "20121401092958";
TimeUnit spanInDays = getDateDiff(str);
System.out.println(spanInDays);
}
public static TimeUnit getDateDiff(String str ){
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date currentDate = new Date();
Date givenDate = null;
Date d2 = null;
try{
givenDate = dateFormat.parse(str);
long diff = currentDate.getTime() - givenDate.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}catch(Exception e){
e.printStackTrace();
}
}
}
I get Compilation Error
DateDifference.java:24: error: incompatible types: long cannot be converted to TimeUnit
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
^
1 error
How to fix that?
The compiler is saying that the return type of the method is not what it expected; you declared it as TimeUnit
but you're returning a value of type long
.
Since that makes sense (you are returning a long
, not a definition of a TimeUnit
), you should adjust the return type:
public static long getDateDiff(String str) {
Your method is
public static
TimeUnit
...
So your method has to return type TimeUnit
. What you have it returning is a long
TimeUnit.Days.convert(diff, TimeUnit.MILLISECONDS)
is type long
Just change the return type or what it is returning to match.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.