2017-04-26 46 views
-1

我有這樣一個字符串210115我想將它表示爲21:01:15任何想法? 我嘗試使用公曆,但它增加了日期它,我不想時間字符串到時間表示法Java

SimpleDateFormat sdf = new SimpleDateFormat("HHmmss"); 
Date date = new Date(); 
try{ 
date = sdf.parse("210115"); 
} 
catch(Exception e){ 
} 

Calendar calendar = GregorianCalendar.getInstance(); 
calendar.setTime(date); 
System.out.print(calendar.getTime()); 

輸出是Thu Jan 01 21:01:15 UTC 1970但我想要的只是21:01:15

感謝。

+2

沒有日期作爲日期對象沒有時間 – Jens

+0

問題是爲什麼即使轉換爲日期,如果你只是想要一個字符串? 只要做: String s =「210115」; String output = s.substring(0,2)+「:」+ s.substring(2,2)+「:」+ s.substring(4,2); –

+0

[在Java字符串中更改日期格式]的可能重複(http://stackoverflow.com/questions/4772425/change-date-format-in-a-java-string) –

回答

2

要輸出格式化的日期,您可以使用另一個SimpleDateFormat對象,並使用所需格式的模式。

在這種情況下,這聽起來像你可能想使用類似

 
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss"); 
System.out.println(outputFormat.format(date)); 

2

所以,你想要的是隻是一個時間,沒有時區。我會推薦使用LocalTime類,這正是這個類,而不是Date類。

LocalTime time = LocalTime.parse("210115", DateTimeFormatter.ofPattern("HHmmss")); 
+0

我正準備自己回答這個問題。另外,'toString()'實現似乎保證了_HH:mm:ss_輸出。 – Magnilex

+0

@Magnilex是的。 – assylias

0

如果妳[R獲得在「」這種格式的日期字符串,你爲什麼要使用日期格式希望它在「21時01分15秒」格式即可。 只需執行字符串操作:

String time="210115"; 
     String newtime=time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6); 
     System.out.println(newtime); 

您將獲得所需的格式。 21:01:15