0
# Date and Time Handling
1
2
Comprehensive date and time utilities through the `DateUtil` class, providing parsing, formatting, calculation, and manipulation operations with enhanced `DateTime` class.
3
4
## Import
5
6
```java
7
import cn.hutool.core.util.DateUtil;
8
import cn.hutool.core.date.DateTime;
9
import cn.hutool.core.date.DateField;
10
import cn.hutool.core.date.DateUnit;
11
```
12
13
## Date Creation and Parsing
14
15
### Date Creation
16
17
```java { .api }
18
// Current date and time
19
public static DateTime date();
20
public static DateTime dateSecond();
21
22
// Create from components
23
public static DateTime date(int year, int month, int day);
24
public static DateTime date(int year, int month, int day, int hour, int minute, int second);
25
26
// Create from timestamp
27
public static DateTime date(long date);
28
public static DateTime date(Date date);
29
```
30
31
### Date Parsing
32
33
```java { .api }
34
// Parse with format
35
public static DateTime parse(CharSequence dateStr, String format);
36
public static DateTime parse(CharSequence dateStr, DatePattern pattern);
37
38
// Parse with auto-detection
39
public static DateTime parse(CharSequence dateStr);
40
public static DateTime parseDate(CharSequence dateStr);
41
public static DateTime parseTime(CharSequence dateStr);
42
public static DateTime parseDateTime(CharSequence dateStr);
43
44
// Parse from timestamp string
45
public static DateTime parseUTC(String utcString);
46
public static DateTime parseCst(String cstString);
47
```
48
49
**Usage Examples:**
50
51
```java
52
// Parse with specific format
53
DateTime dt = DateUtil.parse("2023-12-25 15:30:45", "yyyy-MM-dd HH:mm:ss");
54
55
// Auto-detect common formats
56
DateTime dt1 = DateUtil.parse("2023-12-25");
57
DateTime dt2 = DateUtil.parse("2023/12/25 15:30:45");
58
DateTime dt3 = DateUtil.parse("Dec 25, 2023");
59
60
// Parse ISO formats
61
DateTime utc = DateUtil.parseUTC("2023-12-25T15:30:45Z");
62
```
63
64
## Date Formatting
65
66
### Format to String
67
68
```java { .api }
69
// Format with pattern
70
public static String format(Date date, String format);
71
public static String format(Date date, DatePattern pattern);
72
73
// Common format methods
74
public static String formatDate(Date date);
75
public static String formatTime(Date date);
76
public static String formatDateTime(Date date);
77
78
// ISO formats
79
public static String formatIso8601(Date date);
80
public static String formatHttpDate(Date date);
81
```
82
83
### Predefined Patterns
84
85
```java { .api }
86
// Common date patterns from DatePattern enum
87
DatePattern.NORM_DATE_PATTERN = "yyyy-MM-dd";
88
DatePattern.NORM_TIME_PATTERN = "HH:mm:ss";
89
DatePattern.NORM_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
90
DatePattern.ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";
91
DatePattern.HTTP_DATETIME_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
92
DatePattern.CHINESE_DATE_PATTERN = "yyyy年MM月dd日";
93
```
94
95
**Usage Examples:**
96
97
```java
98
Date now = new Date();
99
100
// Standard formatting
101
String dateStr = DateUtil.format(now, "yyyy-MM-dd HH:mm:ss");
102
String isoStr = DateUtil.formatIso8601(now);
103
104
// Predefined patterns
105
String date = DateUtil.formatDate(now); // "2023-12-25"
106
String time = DateUtil.formatTime(now); // "15:30:45"
107
String datetime = DateUtil.formatDateTime(now); // "2023-12-25 15:30:45"
108
```
109
110
## Date Calculations
111
112
### Date Arithmetic
113
114
```java { .api }
115
// Add/subtract time units
116
public static DateTime offset(Date date, DateField dateField, int offset);
117
public static DateTime offsetDay(Date date, int offset);
118
public static DateTime offsetWeek(Date date, int offset);
119
public static DateTime offsetMonth(Date date, int offset);
120
public static DateTime offsetYear(Date date, int offset);
121
122
// Time zone offset
123
public static DateTime offsetHour(Date date, int offset);
124
public static DateTime offsetMinute(Date date, int offset);
125
public static DateTime offsetSecond(Date date, int offset);
126
```
127
128
### Date Differences
129
130
```java { .api }
131
// Calculate between dates
132
public static long between(Date beginDate, Date endDate, DateUnit unit);
133
public static long betweenDay(Date beginDate, Date endDate);
134
public static long betweenWeek(Date beginDate, Date endDate);
135
public static long betweenMonth(Date beginDate, Date endDate);
136
public static long betweenYear(Date beginDate, Date endDate);
137
138
// Time differences in milliseconds
139
public static long spendMs(long preTime);
140
public static String spendNt(long startNanoTime);
141
```
142
143
**Usage Examples:**
144
145
```java
146
Date now = new Date();
147
148
// Add 5 days
149
DateTime future = DateUtil.offsetDay(now, 5);
150
151
// Subtract 2 months
152
DateTime past = DateUtil.offsetMonth(now, -2);
153
154
// Calculate difference
155
Date start = DateUtil.parse("2023-01-01");
156
Date end = DateUtil.parse("2023-12-31");
157
long days = DateUtil.betweenDay(start, end); // Number of days between dates
158
```
159
160
## Date Ranges and Boundaries
161
162
### Date Range Operations
163
164
```java { .api }
165
// Range creation
166
public static List<DateTime> range(Date startDate, Date endDate, DateField field);
167
public static List<DateTime> rangeToList(Date startDate, Date endDate, DateField field);
168
169
// Date boundaries
170
public static DateTime beginOfDay(Date date);
171
public static DateTime endOfDay(Date date);
172
public static DateTime beginOfWeek(Date date);
173
public static DateTime endOfWeek(Date date);
174
public static DateTime beginOfMonth(Date date);
175
public static DateTime endOfMonth(Date date);
176
public static DateTime beginOfYear(Date date);
177
public static DateTime endOfYear(Date date);
178
```
179
180
### Time Period Checks
181
182
```java { .api }
183
// Check if dates are in same period
184
public static boolean isSameDay(Date date1, Date date2);
185
public static boolean isSameWeek(Date date1, Date date2, boolean isMondayAsFirstDay);
186
public static boolean isSameMonth(Date date1, Date date2);
187
public static boolean isSameYear(Date date1, Date date2);
188
189
// Weekend and weekday checks
190
public static boolean isWeekend(Date date);
191
public static boolean isWeekday(Date date);
192
```
193
194
## Date Comparison
195
196
### Comparison Operations
197
198
```java { .api }
199
// Compare dates
200
public static int compare(Date date1, Date date2);
201
public static boolean isExpired(Date validDate);
202
203
// Before/after checks
204
public static boolean isIn(Date date, Date beginDate, Date endDate);
205
```
206
207
## Calendar and Week Operations
208
209
### Calendar Information
210
211
```java { .api }
212
// Get calendar info
213
public static int year(Date date);
214
public static int month(Date date);
215
public static int dayOfMonth(Date date);
216
public static int dayOfYear(Date date);
217
public static int dayOfWeek(Date date);
218
public static int hour(Date date, boolean is24HourClock);
219
public static int minute(Date date);
220
public static int second(Date date);
221
public static int millisecond(Date date);
222
223
// Week operations
224
public static int weekOfYear(Date date);
225
public static int weekOfMonth(Date date);
226
```
227
228
### Age and Period Calculations
229
230
```java { .api }
231
// Age calculation
232
public static int age(Date birthDay, Date dateToCompare);
233
public static String formatBetween(Date beginDate, Date endDate, BetweenFormatter.Level level);
234
```
235
236
## DateTime Class
237
238
Enhanced Date class with fluent API:
239
240
```java { .api }
241
public class DateTime extends Date {
242
// Constructors
243
public DateTime();
244
public DateTime(Date date);
245
public DateTime(long timeMillis);
246
public DateTime(String dateStr, String format);
247
248
// Fluent operations
249
public DateTime offset(DateField dateField, int offset);
250
public DateTime offsetNew(DateField dateField, int offset);
251
252
// Formatting
253
public String toString(String format);
254
255
// Boundary operations
256
public DateTime beginOfDay();
257
public DateTime endOfDay();
258
public DateTime beginOfWeek();
259
public DateTime endOfWeek();
260
public DateTime beginOfMonth();
261
public DateTime endOfMonth();
262
public DateTime beginOfYear();
263
public DateTime endOfYear();
264
265
// Conversion
266
public long getTime();
267
public String toDateStr();
268
public String toTimeStr();
269
public String toSqlTimestamp();
270
271
// Comparison
272
public boolean isBefore(Date date);
273
public boolean isAfter(Date date);
274
public boolean isWeekend();
275
}
276
```
277
278
**Usage Examples:**
279
280
```java
281
// Create and manipulate DateTime
282
DateTime dt = DateUtil.date()
283
.beginOfDay() // Start of today
284
.offsetDay(7) // Add 7 days
285
.endOfDay(); // End of that day
286
287
// Chaining operations
288
String result = DateUtil.parse("2023-12-25")
289
.offsetMonth(1)
290
.toString("yyyy-MM-dd"); // "2024-01-25"
291
292
// Weekend check
293
boolean weekend = DateUtil.date().isWeekend();
294
```
295
296
## Enums and Constants
297
298
### DateField Enum
299
300
```java { .api }
301
public enum DateField {
302
MILLENNIUM, // 千年
303
CENTURY, // 世纪
304
DECADE, // 十年
305
YEAR, // 年
306
MONTH, // 月
307
WEEK_OF_YEAR, // 一年中的第几周
308
WEEK_OF_MONTH, // 一月中的第几周
309
DAY_OF_YEAR, // 一年中的第几天
310
DAY_OF_MONTH, // 一月中的第几天
311
DAY_OF_WEEK, // 一周中的第几天
312
HOUR_OF_DAY, // 小时(24小时制)
313
HOUR, // 小时(12小时制)
314
MINUTE, // 分钟
315
SECOND, // 秒
316
MILLISECOND // 毫秒
317
}
318
```
319
320
### DateUnit Enum
321
322
```java { .api }
323
public enum DateUnit {
324
MILLISECOND(1),
325
SECOND(1000),
326
MINUTE(60 * 1000),
327
HOUR(60 * 60 * 1000),
328
DAY(24 * 60 * 60 * 1000),
329
WEEK(7 * 24 * 60 * 60 * 1000),
330
MONTH, // Variable length
331
YEAR // Variable length
332
}
333
```
334
335
### Week and Month Enums
336
337
```java { .api }
338
public enum Week {
339
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
340
}
341
342
public enum Month {
343
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
344
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
345
}
346
```
347
348
All date operations handle null inputs gracefully and support both `Date` and `DateTime` objects. The `DateTime` class provides additional functionality and fluent API for complex date manipulations.