當我像這樣的代碼我沒有得到任何錯誤: -關於TimeUnit Day轉換的Java程序有什麼問題?
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();
}
}
}
但是當我這樣的代碼是: -
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();
}
}
}
我得到編譯錯誤
DateDifference.java:24: error: incompatible types: long cannot be converted to TimeUnit
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
^
1 error
如何解決這個問題?
我以爲DIFF其中^指向無法轉換到TimeUnit雖然發現很難理解。 –