2016-12-22 162 views
-2

所以我試圖將時間從納秒轉換爲分鐘。 我的代碼看起來像這樣:爲什麼TimeUnit.convert()不能在Java中正確轉換?

long startTime=System.nanoTime(); 
//some code... 
long endTime=System.nanoTime(); 
long estimatedTime=endTime-startTime; 

long estimatedTime2=TimeUnit.MINUTES.convert(estimatedTime, TimeUnit.NANOSECONDS); 
System.out.println(estimatedTime2 +","+estimatedTime); 

輸出

estimatedTime is always in nanoseconds 
estimatedTime2 is always 0; 

根據的JavaDoc - TimeUnit

public long convert(long sourceDuration, TimeUnit sourceUnit) 

想返回long到estimatedTime2的方法。

什麼是使用此轉換類型的正確形式?

謝謝你!

+1

[MCVE]或[SSCCE ](http://sscce.org)以及觀察和預期的行爲描述。 –

+3

estimatedTime2始終爲0的可能性可能是由於計算的估計時間爲0,因爲在startTime和endTime之間沒有足夠的時間已過去 –

+0

在您嘗試解決估計的時間2並打印出預計的時間之前打印出估計的時間 –

回答

2

除非endTime和startTime之間的差異超過一分鐘,否則答案爲零。請注意,轉換()的返回值是不是float或雙(即沒有小數點)

+0

謝謝!那麼有沒有一種優雅的方式可以將時間轉換成小於60秒的分鐘?而不使用硬編碼的數字來劃分。 –

0

你也可以簡單地用手做沒有全部開銷 -

float minutesElapsed = estimatedTime/1000/1000/1000/60; 

nano/1000 -> micro/1000 -> milli/1000 -> sec/60 -> minutes 
相關問題