Skip to content

Instantly share code, notes, and snippets.

@longforus
Last active November 21, 2019 02:59
Show Gist options
  • Save longforus/a45e9074fe46443a2d12b44705436469 to your computer and use it in GitHub Desktop.
Save longforus/a45e9074fe46443a2d12b44705436469 to your computer and use it in GitHub Desktop.
毫秒时间戳转合适时间长度
/**
* 毫秒时间戳转合适时间长度
*
* @param millis 毫秒时间戳
*
* 小于等于0,返回null
* @param precision 精度
*
* * precision = 0,返回null
* * precision = 1,返回天
* * precision = 2,返回天和小时
* * precision = 3,返回天、小时和分钟
* * precision = 4,返回天、小时、分钟和秒
* * precision >= 5,返回天、小时、分钟、秒和毫秒
*
* @return 合适时间长度
*/
static String millis2FitTimeSpan(int millis, int precision) {
if (millis < 0 || precision <= 0) {
return "";
}
precision = min(precision, 5);
var units = ["天", "小时", "分钟", "秒", "毫秒"];
if (millis == 0) return 0.toString() + units[precision - 1];
var sb = StringBuffer();
var unitLen = [86400000, 3600000, 60000, 1000, 1];
for(var i = 0;i<precision;i++){
if (millis >= unitLen[i]) {
var mode = millis ~/ unitLen[i];
millis -= (mode * unitLen[i]).toInt();
sb.write(mode);
sb.write(units[i]);
}
}
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment