-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeUtils.java
More file actions
61 lines (48 loc) · 2.03 KB
/
Copy pathTimeUtils.java
File metadata and controls
61 lines (48 loc) · 2.03 KB
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
import java.util.concurrent.TimeUnit;
public class TimeUtils {
public static String toRelative(long timeStamp) {
long delta = System.currentTimeMillis() - timeStamp;
if (delta < 0) {
return "just now";
}
long seconds = TimeUnit.MILLISECONDS.toSeconds(delta);
long minutes = TimeUnit.MILLISECONDS.toMinutes(delta);
long hours = TimeUnit.MILLISECONDS.toHours(delta);
long days = TimeUnit.MILLISECONDS.toDays(delta);
if (seconds < 45) {
return "just now";
} else if (seconds < 90) {
return "a minute ago";
} else if (minutes < 45) {
return minutes + " minutes ago";
} else if (minutes < 90) {
return "an hour ago";
} else if (hours < 24) {
return hours + " hours ago";
} else if (hours < 42) {
return "a day ago";
} else if (days < 30) {
return days + " days ago";
} else if (days < 45) {
return "a month ago";
} else {
long months = days / 30;
if (months < 12) {
return months + " months ago";
}
long years = months / 12;
return years == 1 ? "a year ago" : years + " years ago";
}
}
public static void main(String Args[]) {
long now = System.currentTimeMillis();
System.out.println("Testing TimeUtils:");
System.out.println("................");
System.out.println("Current Time: " + toRelative(now));
System.out.println("40 seconds ago: " + toRelative(now - 40_000));
System.out.println("10 minutes ago: " + toRelative(now - (10 * 60 * 1000L)));
System.out.println("5 hours ago: " + toRelative(now - (5 * 60 * 60 * 1000L)));
System.out.println("3 days ago: " + toRelative(now - (3L * 24 * 60 * 60 * 1000)));
System.out.println("400 days ago: " + toRelative(now - (400L * 24 * 60 * 60 * 1000)));
}
}