-
Notifications
You must be signed in to change notification settings - Fork 12
/
HumanReadableDurationFormat.java
84 lines (72 loc) · 2.36 KB
/
HumanReadableDurationFormat.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package kata.kyu4;
public class HumanReadableDurationFormat {
public static String formatDuration(int s) {
int time = s;
int years = s / 31536000;
s -= years * 31536000;
int days = s / 86400;
s -= days * 86400;
int hours = s / 3600;
s -= hours * 3600;
int minutes = s / 60;
s -= minutes * 60;
int seconds = s;
StringBuilder sb = new StringBuilder();
if (time == 0) sb.append("now");
time = processYears(time, years, sb);
time = processDays(time, days, sb);
time = processHours(time, hours, sb);
processMinutes(time, minutes, sb);
processSeconds(seconds, sb);
if (sb.indexOf(",") > 0) sb.replace(sb.lastIndexOf(","), sb.lastIndexOf(",") + 1, " and");
return sb.toString().trim();
}
private static void processSeconds(int seconds, StringBuilder sb) {
if (seconds > 0) {
sb.append(seconds).append(" second");
appendS(seconds, sb);
}
}
private static void processMinutes(int time, int minutes, StringBuilder sb) {
if (minutes > 0) {
sb.append(minutes).append(" minute");
appendS(minutes, sb);
time -= minutes * 60;
postfix(time, sb);
}
}
private static void appendS(int count, StringBuilder sb) {
if (count > 1) sb.append("s");
}
private static void postfix(int time, StringBuilder sb) {
if (time > 0) sb.append(", ");
else sb.append(" ");
}
private static int processHours(int time, int hours, StringBuilder sb) {
if (hours > 0) {
sb.append(hours).append(" hour");
appendS(hours, sb);
time -= hours * 3600;
postfix(time, sb);
}
return time;
}
private static int processDays(int time, int days, StringBuilder sb) {
if (days > 0) {
sb.append(days).append(" day");
appendS(days, sb);
time -= days * 86400;
postfix(time, sb);
}
return time;
}
private static int processYears(int time, int years, StringBuilder sb) {
if (years > 0) {
sb.append(years).append(" year");
appendS(years, sb);
time -= years * 31536000;
postfix(time, sb);
}
return time;
}
}