2012-09-15 22 views
1

我想在我的Util類中創建一個靜態方法,該方法將返回日期格式的當前時間。所以我已經嘗試了下面的代碼,但它總是返回同一時間。靜態方法總是返回同一時間

private static Date date = new Date(); 
private static SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a"); 

public static String getCurrentDate() { 
    return formatter.format(date.getTime()); 
} 

如何在不創建Util類的實例的情況下以我的特定格式獲取更新時間。可能嗎。

回答

6

自從您重複使用相同的Date對象以來,您總會得到相同的時間。日期對象是在解析類時創建的。爲了得到當前的時間,每次使用:

private static SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a"); 

public static String getCurrentDate() { 
    Date date = new Date(); 
    return timeFormatter.format(date); 
} 

甚至

public static String getCurrentDate() { 
    Date date = new Date(); 
    SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a"); 
    return timeFormatter.format(date); 
} 

爲的SimpleDateFormat不是線程安全的。

正如您只想要當前時間,甚至不需要創建新日期。

public static String getCurrentDate() { 
    SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a"); 
    return timeFormatter.format(System.currentTimeMillis()); 
} 

如果你只是想輸出,而不是解析你可以使用

public static String getCurrentDate() { 
    return String.format("%1$tr", System.currentTimeMillis()); 
} 
+0

我不知道下投票是對的能力,但你是正確的軌道上。我建議使用[System.currentTimeMillis()](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()) – MadProgrammer