嗨,这段代码怎么样?
example)
0 ms -> 0 ms
846 ms -> 846ms
1,000 ms -> 1s
1,034 ms -> 1s 34ms
60,000 ms -> 1m
94,039 ms -> 1m 34s 39ms
3,600,000 ms -> 1h
61,294,039 ms -> 17h 1m 34s 39ms
86,400,000 ms -> 1d
406,894,039 ms -> 4d 17h 1m 34s 39ms
31,536,000,000 ms -> 1y
50,428,677,591 ms -> 1y 218d 15h 57m 57s 591ms
/**
*
* @since 2018. 1. 9.
* @author Park_Jun_Hong_(fafanmama_at_naver_com)
*/
public class TimeUtils {
/**
*
* @since 2018. 1. 9.
*/
private TimeUtils() {
}
private static void appendTimeAndUnit(StringBuffer timeBuf, long time, String unit) {
if (time < 1) {
return;
}
timeBuf.append(time);
timeBuf.append(unit);
}
private static void prependTimeAndUnit(StringBuffer timeBuf, long time, String unit) {
if (time < 1) {
return;
}
if (timeBuf.length() > 0) {
timeBuf.insert(0, " ");
}
timeBuf.insert(0, unit);
timeBuf.insert(0, time);
}
/**
* Provide the Millisecond time value in {year}y {day}d {hour}h {minute}m {second}s {millisecond}ms. <br>
* Omitted if there is no value for that unit.
*
* @param timeInMillis
* @return
*
* @since 2018. 1. 9.
*/
public static String toYYYYHHmmssS(long timeInMillis) {
if (timeInMillis < 1) {
return "0 ms";
}
StringBuffer timeBuf = new StringBuffer();
long millis = timeInMillis % 1000;
appendTimeAndUnit(timeBuf, millis, "ms");
// second (1000ms) & above
long time = timeInMillis/1000;
if (time < 1) {
return timeBuf.toString();
}
long seconds = time % 60;
prependTimeAndUnit(timeBuf, seconds, "s");
// minute(60s) & above
time = time/60;
if (time < 1) {
return timeBuf.toString();
}
long minutes = time % 60;
prependTimeAndUnit(timeBuf, minutes, "m");
// hour(60m) & above
time = time/60;
if (time < 1) {
return timeBuf.toString();
}
long hours = time % 24;
prependTimeAndUnit(timeBuf, hours, "h");
// day(24h) & above
time = time/24;
if (time < 1) {
return timeBuf.toString();
}
long day = time % 365;
prependTimeAndUnit(timeBuf, day, "d");
// year(365d) ...
time = time/365;
if (time < 1) {
return timeBuf.toString();
}
prependTimeAndUnit(timeBuf, time, "y");
return timeBuf.toString();
}
}
那么你为什么不利用存在(本机)的日期时间类? – 2013-10-29 19:33:19
为什么'%24'在几天内?一个月有24天吗? –
@ user2511414:你错在本机和框架。本地意味着用os本地语言编写,无论是什么(在本例中为C/C++),它都可以属于框架或任何应用程序。您所指的类(如SimpleDateFormat)属于框架,但是它们是否是本地的并不相关。 – njzk2