2014-09-22 55 views
1

我試圖使用SimpleDateFormat格式化由3個整數表示的日期。 它看起來像這樣:SimpleDateFormat android未按預期格式化

... 
SimpleDateFormat sdfHour = new SimpleDateFormat("HH"); 
SimpleDateFormat sdfMinute = new SimpleDateFormat("mm"); 
SimpleDateFormat sdfSecond = new SimpleDateFormat("ss"); 

Calendar c = Calendar.getInstance(); 
c.setTimeZone(TimeZone.getDefault()); 
int hours = c.get(Calendar.HOUR_OF_DAY); 
int minutes = c.get(Calendar.MINUTE); 
int seconds = c.get(Calendar.SECOND); 

String string_hours = sdfHour.format(hours); 
String string_minutes = sdfMinute.format(minutes); 
String string_seconds = sdfSecond.format(seconds); 

Log.d("tag", "Time string is: " + string_hours + ":" + string_minutes + ":" + string_seconds); 

輸出總是

Time string is: 19:00:00 

我在做什麼錯在這裏?

+1

您期望的是什麼? – 2014-09-22 10:38:26

回答

4

SimpleDateFormat.format需要日期,而不是int。您正在使用的方法,即接受長時間的重載版本,實際上期望從時代開始毫秒,而不是像您一樣每分鐘或一秒鐘。

使用它應該是正確的做法:

SimpleDateFormat sdfHour = new SimpleDateFormat("HH:mm:ss"); 
String timeString = sdfHour.format(new Date()); 

使用「新的Date()」在這個例子中,會給你的當前時間。如果你需要格式化一些其他的時間(比如一小時前,或者某個數據庫中的東西等),通過格式化正確的Date實例。

如果您需要分離,出於某種原因,那麼你仍然可以使用,但是,這個另一種方式:

SimpleDateFormat sdfHour = new SimpleDateFormat("HH"); 
SimpleDateFormat sdfMinute = new SimpleDateFormat("mm"); 
SimpleDateFormat sdfSecond = new SimpleDateFormat("ss"); 

Date now = new Date(); 

String string_hours = sdfHour.format(now); 
String string_minutes = sdfMinute.format(now); 
String string_seconds = sdfSecond.format(now); 
1

不能使用SimpleDateFormat這樣的:

SimpleDateFormat sdfHour = new SimpleDateFormat("HH"); 
SimpleDateFormat sdfMinute = new SimpleDateFormat("mm"); 
SimpleDateFormat sdfSecond = new SimpleDateFormat("ss"); 

使用這樣的:

long timeInMillis = System.currentTimeMillis(); 
Calendar cal1 = Calendar.getInstance(); 
cal1.setTimeInMillis(timeInMillis); 
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); 
String dateformatted = dateFormat.format(cal1.getTime()); 

參考this

1

嘗試是這樣的:

Calendar cal = Calendar.getInstance(); 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
String CurrentTime = sdf.format(cal.getTime()); 
+1

希望這可以幫助你! – 2014-09-22 10:40:30

+0

簡單和工作。謝謝! – Marcus 2014-09-22 10:47:14

+0

如果它適合你,那麼請接受我的回答 – 2014-09-22 10:48:03

1

要調用錯誤format方法。你應該提供一個Date參數中合適的一個,而是你正使用該one,從Format類繼承:

public final String format(Object obj) 

爲什麼它的工作?由於Java中的自動裝箱過程。您提供了一個int,它會自動裝箱到Integer,這是Object的繼任者