2012-09-17 71 views
5

我需要從毫秒格式化秒和分鐘。我正在使用countdownTimer。有沒有人有sugestions?我看着喬達的時間。但所有我需要的是一種格式,所以我有1:05而不是1:5。感謝格式化秒和分鐘

private void walk() { 
    new CountDownTimer(15000, 1000) { 
     @Override 
     public void onFinish() { 
      lapCounter++; 
      lapNumber.setText("Lap Number: " + lapCounter); 
      run(); 
     } 

     @Override 
     public void onTick(long millisUntilFinished) { 
      text.setText("Time left:" + millisUntilFinished/1000); 
     } 
    }.start(); 
} 
+0

你已經看過成SimpleNumberFormat?或者,如果總數小於10,則可以在整數左側附加一個「0」。 – BlackVegetable

+0

我不確定它是否會滿足您的整個需求,但它可能值得一看[PrettyTime](http:///ocpsoft.org/prettytime/ – MadProgrammer

回答

26

你可以通過做這樣的一個真正的懶辦法標準的日期格式化類,但這可能有點重量級。我只是使用String.format方法。例如:

int minutes = time/(60 * 1000); 
int seconds = (time/1000) % 60; 
String str = String.format("%d:%02d", minutes, seconds); 
+0

太棒了!那正是我想要的!即時通訊不知道我明白「%d:%02d」我自己嘗試了這一點,並沒有得到它的權利。謝謝! –

+1

%表示置換,0表示置零,2表示置寬,d表示十進制數。以下是文檔:http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html –

6

只要你知道你會不會有超過60分鐘只作一個日期和使用SimpleDateFormat

public void onTick(long millisUntilFinished) { 
    SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss"); 
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 
    Date date = new Date(millisUntilFinished); 
    text.setText("Time left:" + dateFormat.format(date)); 
} 
0

我使用了Apache Commons StopWatch類。它的toString方法的默認輸出類似ISO8601,小時:分鐘:秒。毫秒。

Example of Apache StopWatch

2

我會使用

org.apache.commons.lang.time.DurationFormatUtils.formatDuration(millisUntilFinished, "mm:ss") 
相關問題