2015-05-20 27 views
0

當我像這樣的代碼我沒有得到任何錯誤: -關於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 

如何解決這個問題?

回答

4

編譯器說這個方法的返回類型不是它所期望的;您將其聲明爲TimeUnit,但您返回的是long類型的值。

由於這是有道理的(你是返回一個long,一個TimeUnit的不是定義),你應該調整的返回類型:

public static long getDateDiff(String str) { 
+0

我以爲DIFF其中^指向無法轉換到TimeUnit雖然發現很難理解。 –

3

你的方法

public staticTimeUnit ...

所以你的方法必須返回類型TimeUnit。你有它返回的是一個long

TimeUnit.Days.convert(diff, TimeUnit.MILLISECONDS)是類型long

只是改變返回類型或什麼它返回匹配。

希望這會有所幫助。