2016-04-23 78 views
0

我要添加日期甲酸(H:MM:SS:SSS).I沒以下各項添加編號,以日期(H:MM:SS:SSS)格式

Date time1; 
    Date time2; 
    String result1; 
    SimpleDateFormat formatter; 
    formatter = new SimpleDateFormat("H:mm:ss:SSS"); 
    time1 = new Date(0,0,0,0,0,5); 
    time2=new Date(0,0,0,0,0,5); 

的TIME1的輸出是0:00:05:000。現在我想添加這兩個時間,並使0:00:10:000。但time1+time2是不可能的。有沒有辦法做到這一點?

+0

這真的不要緊,你如何格式化你的'日期對象的輸出,他們仍然是日期(當然,它們代表了一個瞬間,更準確)。那麼,究竟應該添加兩個「日期」呢?你的問題沒有意義。 – Seelenvirtuose

+0

我需要格式化的輸出。這不是關於添加兩個日期。它是關於添加這種格式的兩個數字。 –

回答

3

您可以使用日曆您的要求:

Calendar calendar = Calendar.getInstance(); 
    calendar.setTime(new Date()); 
    calendar.set(Calendar.HOUR_OF_DAY,0); 
    calendar.set(Calendar.MINUTE,0); 
    calendar.set(Calendar.SECOND,5); 
    calendar.set(Calendar.MILLISECOND,0); 

    System.out.println(formatter.format(calendar.getTime())); 

    Calendar another = Calendar.getInstance(); 
    another.setTime(calendar.getTime()); 
    another.set(Calendar.HOUR_OF_DAY,0); 
    another.set(Calendar.MINUTE,0); 
    another.set(Calendar.SECOND,calendar.get(Calendar.SECOND)+5); 
    another.set(Calendar.MILLISECOND,0); 

    System.out.println(formatter.format(another.getTime())); 

OUTPUT:

0:00:05:000 
0:00:10:000 

這裏是Java文檔的Calendar

+0

你的回答是正確的根據我的問題。實際上我想用一個會增加5秒時間的循環。在你的方式中,你添加了第二個5。這對我來說很好,我可以在整個日期加5,而不僅僅是秒。謝謝 –

+0

好的。爲此,您只需計算需要添加的秒數,然後使用日曆添加秒數。 – Unknown

+0

我試過循環,沒有額外的計算第二是必要的。只需用「second + i」替換「second + 5」表達式,它會自動處理分鐘和小時。謝啦。 –

1

new Date(time1.getTime() + time2.getTime())應該這樣做。

getTime()返回自1970年1月1日00:00:00 GMT以來的毫秒數。
new Date(0, 0, 0, 0, 0, 0)等於1970年1月1日,格林威治標準時間00:00:00。所以基本上只有time1.getTime()time2.getTime()中的5秒的毫秒數,所以你可以將它們求和並將其轉換回Date對象。