1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.util;
15
16 import java.util.Calendar;
17 import java.util.Date;
18 import java.util.TimeZone;
19
20 import org.junit.jupiter.api.Assertions;
21 import org.junit.jupiter.api.Test;
22
23 public class TimeUtilTest {
24
25 @Test
26 public void testSecond() {
27
28 long now = 1164042317522L;
29
30 long expected = 1164042318000L;
31 long computed = TimeUtil.computeStartOfNextSecond(now);
32 Assertions.assertEquals(expected - now, 478);
33 Assertions.assertEquals(expected, computed);
34 }
35
36 @Test
37 public void testMinute() {
38
39 long now = 1164042317522L;
40
41 long expected = 1164042360000L;
42
43 long computed = TimeUtil.computeStartOfNextMinute(now);
44 Assertions.assertEquals(expected - now, 1000 * 42 + 478);
45 Assertions.assertEquals(expected, computed);
46 }
47
48 @Test
49 public void testHour() {
50
51 long now = 1164045917522L;
52 now = correctBasedOnTimeZone(now);
53
54 long expected = 1164049200000L;
55 expected = correctBasedOnTimeZone(expected);
56
57 long computed = TimeUtil.computeStartOfNextHour(now);
58 Assertions.assertEquals(expected - now, 1000 * (42 + 60 * 54) + 478);
59 Assertions.assertEquals(expected, computed);
60 }
61
62 @Test
63 public void testDay() {
64
65 long now = 1164045917522L;
66 now = correctBasedOnTimeZone(now);
67
68 long expected = 1164067200000L;
69 expected = correctBasedOnTimeZone(expected);
70 long computed = TimeUtil.computeStartOfNextDay(now);
71
72 Assertions.assertEquals(expected - now, 1000 * (3600 * 5 + 60 * 54 + 42) + 478);
73 Assertions.assertEquals(expected, computed);
74 }
75
76 @Test
77 public void testWeek() {
78
79 long now = 1164045917522L;
80 now = correctBasedOnTimeZone(now);
81
82 long expected = 1164499200000L;
83 expected = correctBasedOnTimeZone(expected);
84
85 Calendar cal = Calendar.getInstance();
86 cal.setTime(new Date(now));
87
88 int dayOffset = cal.getFirstDayOfWeek() - Calendar.SUNDAY;
89 if (dayOffset != 0) {
90 expected += 24L * 3600 * 1000 * (cal.getFirstDayOfWeek() - Calendar.SUNDAY);
91 }
92
93 long computed = TimeUtil.computeStartOfNextWeek(now);
94
95
96
97 Assertions.assertEquals(expected - now, 1000 * (3600 * (5 + 24 * (5 + dayOffset)) + 60 * 54 + 42) + 478);
98 Assertions.assertEquals(expected, computed);
99 }
100
101 @Test
102 public void testMonth() {
103
104 long now = 1164045917522L;
105 now = correctBasedOnTimeZone(now);
106
107 long expected = 1164931200000L;
108 expected = correctBasedOnTimeZone(expected);
109
110 long computed = TimeUtil.computeStartOfNextMonth(now);
111 Assertions.assertEquals(expected - now, 1000 * (3600 * (5 + 24 * 10) + 60 * 54 + 42) + 478);
112 Assertions.assertEquals(expected, computed);
113 }
114
115 private long correctBasedOnTimeZone(long gmtLong) {
116 int offset = TimeZone.getDefault().getRawOffset();
117 return gmtLong - offset;
118 }
119
120 }