2012年4月21日 星期六

將時間差(微秒)格式化成時間

參考資料:Java 毫秒轉換為(天:時:分:秒)方法

稍微做了一點修正,雖然還是覺得效率稍微差了一點,應該有些乘法可以省掉的
不過暫時先這樣就好 XD

public String timeFormatter(long ms) {
  int ss = 1000;
  int mi = 60000;
  int hh = 3600000;
  int dd = 864000000;
  
  long day = ms / dd;
  long hour = (ms - day * dd) / hh;
  long minute = (ms - day * dd - hour * hh) / mi;
  long second = (ms - day * dd - hour * hh - minute * mi) / ss;
  long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
  String strDay = day < 10 ? "0" + day : String.valueOf(day);
  String strHour = hour < 10 ? "0" + hour : String.valueOf(hour);
  String strMinute = minute < 10 ? "0" + minute : String.valueOf(minute);
  String strSecond = second < 10 ? "0" + second : String.valueOf(second);
  String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : String.valueOf(milliSecond);
  strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : strMilliSecond;
  return strDay + "d," + strHour + ":" + strMinute + ":" + strSecond + "." + strMilliSecond;
}

沒有留言: