Hallo, wie wäre es mit diesem Code?
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();
}
}
also warum nutzen Sie nicht (native) date time classes ?! –
Warum "% 24" an Tagen? Gibt es 24 Tage in einem Monat? –
@ user2511414: Sie verwechseln natives und Framework. Nativ bedeutet, dass es in der Muttersprache des Betriebssystems geschrieben ist, was auch immer das ist (in diesem Fall C/C++), und es kann zum Framework oder zu jeder App gehören. Die Klassen, auf die Sie sich beziehen (z. B. SimpleDateFormat), gehören zum Framework, aber ob sie nativ sind oder nicht, ist nicht relevant. – njzk2