forked from assertj/assertj
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDates.java
More file actions
382 lines (344 loc) · 13.3 KB
/
Dates.java
File metadata and controls
382 lines (344 loc) · 13.3 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2014 the original author or authors.
*/
package org.assertj.core.util;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Utility methods related to dates.
*
* @author Joel Costigliola
* @author Mikhail Mazursky
*/
public class Dates {
/**
* ISO 8601 date format (yyyy-MM-dd), example : <code>2003-04-23</code>
*/
private static final DateFormat ISO_DATE_FORMAT = newIsoDateFormat();
/**
* ISO 8601 local date-time format (yyyy-MM-dd'T'HH:mm:ss), example : <code>2003-04-26T13:01:02</code>
*/
private static final DateFormat ISO_DATE_TIME_FORMAT = newIsoDateTimeFormat();
/**
* ISO 8601 local date-time format with millisecond (yyyy-MM-dd'T'HH:mm:ss.SSS), example :
* <code>2003-04-26T03:01:02.999</code>
*/
private static final DateFormat ISO_DATE_TIME_FORMAT_WITH_MS = newIsoDateTimeWithMsFormat();
/**
* ISO 8601 date format (yyyy-MM-dd), example : <code>2003-04-23</code>
*/
public static DateFormat newIsoDateFormat() {
return new SimpleDateFormat("yyyy-MM-dd");
}
/**
* ISO 8601 date-time format (yyyy-MM-dd'T'HH:mm:ss), example : <code>2003-04-26T13:01:02</code>
*/
public static DateFormat newIsoDateTimeFormat() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
}
/**
* ISO 8601 date-time format with millisecond (yyyy-MM-dd'T'HH:mm:ss.SSS), example :
* <code>2003-04-26T03:01:02.999</code>
*/
public static DateFormat newIsoDateTimeWithMsFormat() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
}
/**
* Formats the given date using the ISO 8601 date-time format (yyyy-MM-dd'T'HH:mm:ss).<br> Method in synchronized
* because SimpleDateFormat is not thread safe (sigh).
* <p/>
* Returns null if given the date is null.
*
* @param date the date to format.
* @return the formatted date or null if given the date was null.
*/
public static synchronized String formatAsDatetime(Date date) {
return date == null ? null : ISO_DATE_TIME_FORMAT.format(date);
}
/**
* Formats the given date using the ISO 8601 date-time format with millisecond (yyyy-MM-dd'T'HH:mm:ss:SSS).<br> Method
* in synchronized because SimpleDateFormat is not thread safe (sigh).
* <p/>
* Returns null if given the date is null.
*
* @param date the date to format.
* @return the formatted date or null if given the date was null.
*/
public static synchronized String formatAsDatetimeWithMs(Date date) {
return date == null ? null : ISO_DATE_TIME_FORMAT_WITH_MS.format(date);
}
/**
* Formats the date of the given calendar using the ISO 8601 date-time format (yyyy-MM-dd'T'HH:mm:ss).<br> Method is
* thread safe.
* <p/>
* Returns null if the given calendar is null.
*
* @param calendar the calendar to format.
* @return the formatted calendar or null if the given calendar was null.
*/
public static String formatAsDatetime(Calendar calendar) {
return calendar == null ? null : formatAsDatetime(calendar.getTime());
}
/**
* Utility method to parse a Date following {@link #ISO_DATE_FORMAT}, returns null if the given String is null.
*
* @param dateAsString the string to parse as a Date following {@link #ISO_DATE_FORMAT}
* @return the corresponding Date or null if the given String is null.
* @throws RuntimeException encapsulating ParseException if the string can't be parsed as a Date
*/
public static synchronized Date parse(String dateAsString) {
try {
return dateAsString == null ? null : ISO_DATE_FORMAT.parse(dateAsString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Utility method to parse a Date following {@link #ISO_DATE_TIME_FORMAT}, returns null if the given String is null.
* <p> Example:
* <pre><code class='java'>
* Date date = parseDatetime("2003-04-26T03:01:02");
* </code></pre>
* </p>
*
* @param dateAsString the string to parse as a Date following {@link #ISO_DATE_TIME_FORMAT}
* @return the corresponding Date with time details or null if the given String is null.
* @throws RuntimeException encapsulating ParseException if the string can't be parsed as a Date
*/
public static synchronized Date parseDatetime(String dateAsString) {
try {
return dateAsString == null ? null : ISO_DATE_TIME_FORMAT.parse(dateAsString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Utility method to parse a Date following {@link #ISO_DATE_TIME_FORMAT_WITH_MS}, returns null if the given String is
* null. <p> Example:
* <pre><code class='java'>
* Date date = parseDatetimeWithMs("2003-04-26T03:01:02.999");
* </code></pre>
* </p>
*
* @param dateAsString the string to parse as a Date following {@link #ISO_DATE_TIME_FORMAT_WITH_MS}
* @return the corresponding Date with time details or null if the given String is null.
* @throws RuntimeException encapsulating ParseException if the string can't be parsed as a Date
*/
public static synchronized Date parseDatetimeWithMs(String dateAsString) {
try {
return dateAsString == null ? null : ISO_DATE_TIME_FORMAT_WITH_MS.parse(dateAsString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Converts the given Date to Calendar, returns null if the given Date is null.
*
* @param date the date to convert to a Calendar.
* @return the Calendar corresponding to the given Date or null if the given Date is null.
*/
public static Calendar toCalendar(Date date) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
/**
* Extracts the year of the given Date.
*
* @param date the date to extract the year from - must not be null.
* @return the year of the given Date
* @throws NullPointerException if given Date is null
*/
public static int yearOf(Date date) {
return toCalendar(date).get(Calendar.YEAR);
}
/**
* Dates Extracts the month of the given Date <b>starting at 1</b> (January=1, February=2, ...).
*
* @param date the date to extract the month from - must not be null.
* @return the month of the given Date <b>starting at 1</b> (January=1, February=2, ...)
* @throws NullPointerException if given Date is null
*/
public static int monthOf(Date date) {
return toCalendar(date).get(Calendar.MONTH) + 1; // based 1 month (January=1)
}
/**
* Dates Extracts the day of month of the given Date.
*
* @param date the date to extract the day of month from - must not be null.
* @return the day of month of the given Date
* @throws NullPointerException if given Date is null
*/
public static int dayOfMonthOf(Date date) {
return toCalendar(date).get(Calendar.DAY_OF_MONTH);
}
/**
* Extracts the day of week of the given Date, returned value follows {@link Calendar#DAY_OF_WEEK} .
*
* @param date the date to extract the day of week from - must not be null.
* @return the day of week of the given Date
* @throws NullPointerException if given Date is null
*/
public static int dayOfWeekOf(Date date) {
return toCalendar(date).get(Calendar.DAY_OF_WEEK);
}
/**
* Extracts the hour of day if the given Date (24-hour clock).
*
* @param date the date to extract the hour of day from - must not be null.
* @return the hour of day of the given Date (24-hour clock)
* @throws NullPointerException if given Date is null
*/
public static int hourOfDayOf(Date date) {
return toCalendar(date).get(Calendar.HOUR_OF_DAY);
}
/**
* Dates Extracts the minute of the given Date.
*
* @param date the date to extract the minute from - must not be null.
* @return the minute of the given Date
* @throws NullPointerException if given Date is null
*/
public static int minuteOf(Date date) {
return toCalendar(date).get(Calendar.MINUTE);
}
/**
* Extracts the second of the given Date.
*
* @param date the date to extract the second from - must not be null.
* @return the second of the given Date
* @throws NullPointerException if given Date is null
*/
public static int secondOf(Date date) {
return toCalendar(date).get(Calendar.SECOND);
}
/**
* Extracts the millisecond of the given Date.
*
* @param date the date to extract the millisecond from - must not be null.
* @return the millisecond of the given Date
* @throws NullPointerException if given Date is null
*/
public static int millisecondOf(Date date) {
return toCalendar(date).get(Calendar.MILLISECOND);
}
/**
* Compute the time difference between the two given dates in milliseconds, it always gives a positive result.
*
* @param date1 the first date.
* @param date2 the second date.
* @return the difference between the two given dates in milliseconds
* @throws IllegalArgumentException if one a the given Date is null.
*/
public static long timeDifference(Date date1, Date date2) {
if (date1 == null || date2 == null) throw new IllegalArgumentException("Expecting date parameter not to be null");
return Math.abs(date1.getTime() - date2.getTime());
}
/**
* Returns a copy of the given date without the time part (which is set to 00:00:00), for example :<br>
* <code>truncateTime(2008-12-29T23:45:12)</code> will give <code>2008-12-29T00:00:00</code>.
* <p/>
* Returns null if the given Date is null.
*
* @param date we want to get the day part (the parameter is read only).
* @return the truncated date.
*/
public static Date truncateTime(Date date) {
if (date == null) return null;
Calendar cal = toCalendar(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date now() {
return new Date();
}
public static Date yesterday() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
public static Date tomorrow() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
/**
* Utility method to display a human readable time difference.
*
* @param date1
* @param date2
* @return a human readable time difference.
*/
public static String formatTimeDifference(final Date date1, final Date date2) {
// difference in ms, s, m, h, d
final long millisecondsDiff = timeDifference(date1, date2);
final long secondsDiff = millisecondsDiff / SECONDS.toMillis(1);
final long minutesDiff = millisecondsDiff / MINUTES.toMillis(1);
final long hoursDiff = millisecondsDiff / HOURS.toMillis(1);
final long daysDiff = millisecondsDiff / DAYS.toMillis(1);
// date field difference
final long hourFieldDiff = hoursDiff - DAYS.toHours(daysDiff);
final long minuteFieldDiff = minutesDiff - HOURS.toMinutes(hoursDiff);
final long secondFieldDiff = secondsDiff - MINUTES.toSeconds(minutesDiff);
final long millisecondsFieldDiff = millisecondsDiff % SECONDS.toMillis(1);
StringBuilder result = new StringBuilder();
if (daysDiff > 0) result.append(format("%dd", daysDiff));
if (hourFieldDiff > 0) {
if (daysDiff > 0 && minuteFieldDiff == 0 && secondFieldDiff == 0 && millisecondsFieldDiff == 0) {
// hour diff field is the last field that differs but not the only one
result.append(" and ");
} else if (daysDiff > 0) {
result.append(" ");
}
result.append(format("%dh", hourFieldDiff));
}
if (minuteFieldDiff > 0) {
final boolean notFirstDiff = daysDiff > 0 || hourFieldDiff > 0;
if (notFirstDiff && secondFieldDiff == 0 && millisecondsFieldDiff == 0) {
// min diff field is the last field that differs but not the only one
result.append(" and ");
} else if (notFirstDiff) {
result.append(" ");
}
result.append(format("%dm", minuteFieldDiff));
}
if (secondFieldDiff > 0) {
final boolean notFirstDiff = daysDiff > 0 || hourFieldDiff > 0 || minuteFieldDiff > 0;
if (notFirstDiff && millisecondsFieldDiff == 0) {
// seconds diff field is the last field that differs but not the only one
result.append(" and ");
} else if (notFirstDiff) {
result.append(" ");
}
result.append(format("%ds", secondFieldDiff));
}
if (millisecondsFieldDiff > 0) {
if (result.length() > 0) result.append(" and ");
result.append(format("%dms", millisecondsFieldDiff));
}
return result.toString();
}
}