0
# Parsing and Factory Methods
1
2
Static methods for parsing temporal objects from strings with custom patterns and creating temporal objects through factory methods.
3
4
## Capabilities
5
6
### Parsing Methods
7
8
Static parsing methods for converting strings to temporal objects using custom DateTimeFormatter patterns.
9
10
```groovy { .api }
11
/**
12
* Parse text into a LocalDate using the provided pattern.
13
*/
14
LocalDate parse(LocalDate type, CharSequence text, String pattern)
15
16
/**
17
* Parse text into a LocalDateTime using the provided pattern.
18
*/
19
LocalDateTime parse(LocalDateTime type, CharSequence text, String pattern)
20
21
/**
22
* Parse text into a LocalTime using the provided pattern.
23
*/
24
LocalTime parse(LocalTime type, CharSequence text, String pattern)
25
26
/**
27
* Parse text into a MonthDay using the provided pattern.
28
*/
29
MonthDay parse(MonthDay type, CharSequence text, String pattern)
30
31
/**
32
* Parse text into an OffsetDateTime using the provided pattern.
33
*/
34
OffsetDateTime parse(OffsetDateTime type, CharSequence text, String pattern)
35
36
/**
37
* Parse text into an OffsetTime using the provided pattern.
38
*/
39
OffsetTime parse(OffsetTime type, CharSequence text, String pattern)
40
41
/**
42
* Parse text into a Year using the provided pattern.
43
*/
44
Year parse(Year type, CharSequence text, String pattern)
45
46
/**
47
* Parse text into a YearMonth using the provided pattern.
48
*/
49
YearMonth parse(YearMonth type, CharSequence text, String pattern)
50
51
/**
52
* Parse text into a ZonedDateTime using the provided pattern.
53
*/
54
ZonedDateTime parse(ZonedDateTime type, CharSequence text, String pattern)
55
```
56
57
**Usage Examples:**
58
59
```groovy
60
import java.time.*
61
62
// LocalDate parsing
63
def date1 = LocalDate.parse('2024-12-25', 'yyyy-MM-dd')
64
def date2 = LocalDate.parse('Dec 25, 2024', 'MMM dd, yyyy')
65
def date3 = LocalDate.parse('25/12/24', 'dd/MM/yy')
66
67
println "Parsed dates: ${date1}, ${date2}, ${date3}"
68
69
// LocalDateTime parsing
70
def datetime1 = LocalDateTime.parse('2024-12-25 14:30:00', 'yyyy-MM-dd HH:mm:ss')
71
def datetime2 = LocalDateTime.parse('Dec 25, 2024 2:30 PM', 'MMM dd, yyyy h:mm a')
72
73
println "Parsed datetimes: ${datetime1}, ${datetime2}"
74
75
// LocalTime parsing
76
def time1 = LocalTime.parse('14:30:45', 'HH:mm:ss')
77
def time2 = LocalTime.parse('2:30 PM', 'h:mm a')
78
def time3 = LocalTime.parse('14:30:45.123', 'HH:mm:ss.SSS')
79
80
println "Parsed times: ${time1}, ${time2}, ${time3}"
81
82
// Year parsing
83
def year1 = Year.parse('2024', 'yyyy')
84
def year2 = Year.parse('24', 'yy')
85
86
// YearMonth parsing
87
def yearMonth1 = YearMonth.parse('2024-12', 'yyyy-MM')
88
def yearMonth2 = YearMonth.parse('Dec 2024', 'MMM yyyy')
89
90
// MonthDay parsing
91
def monthDay1 = MonthDay.parse('12-25', 'MM-dd')
92
def monthDay2 = MonthDay.parse('Dec 25', 'MMM dd')
93
94
println "Year: ${year1}, YearMonth: ${yearMonth1}, MonthDay: ${monthDay1}"
95
```
96
97
### Offset and Zoned Parsing
98
99
Parsing temporal objects that include timezone or offset information.
100
101
**Usage Examples:**
102
103
```groovy
104
import java.time.*
105
106
// OffsetDateTime parsing
107
def offsetDateTime1 = OffsetDateTime.parse('2024-12-25T14:30:00+05:30', "yyyy-MM-dd'T'HH:mm:ssXXX")
108
def offsetDateTime2 = OffsetDateTime.parse('2024-12-25 14:30:00 +0530', 'yyyy-MM-dd HH:mm:ss Z')
109
110
// OffsetTime parsing
111
def offsetTime1 = OffsetTime.parse('14:30:00+05:30', 'HH:mm:ssXXX')
112
def offsetTime2 = OffsetTime.parse('2:30 PM +0530', 'h:mm a Z')
113
114
// ZonedDateTime parsing
115
def zonedDateTime1 = ZonedDateTime.parse('2024-12-25T14:30:00 America/New_York', "yyyy-MM-dd'T'HH:mm:ss VV")
116
def zonedDateTime2 = ZonedDateTime.parse('Dec 25, 2024 2:30 PM EST', 'MMM dd, yyyy h:mm a z')
117
def zonedDateTime3 = ZonedDateTime.parse('2024/12/25 14:30 Eastern Standard Time', 'yyyy/MM/dd HH:mm zzzz')
118
119
println "Offset DateTime: ${offsetDateTime1}"
120
println "Offset Time: ${offsetTime1}"
121
println "Zoned DateTime: ${zonedDateTime1}"
122
```
123
124
### Pattern Reference
125
126
Common DateTimeFormatter pattern symbols for parsing operations.
127
128
**Usage Examples:**
129
130
```groovy
131
import java.time.*
132
133
// Date patterns
134
def patterns = [
135
'yyyy-MM-dd', // 2024-12-25
136
'dd/MM/yyyy', // 25/12/2024
137
'MMM dd, yyyy', // Dec 25, 2024
138
'EEEE, MMMM dd, yyyy', // Wednesday, December 25, 2024
139
'dd-MMM-yy', // 25-Dec-24
140
'yyyyMMdd', // 20241225
141
'yyyy-DDD' // 2024-360 (day of year)
142
]
143
144
def dateString = '2024-12-25'
145
patterns.each { pattern ->
146
try {
147
def parsed = LocalDate.parse(dateString, pattern)
148
println "${pattern}: ${parsed}"
149
} catch (Exception e) {
150
println "${pattern}: Failed to parse '${dateString}'"
151
}
152
}
153
154
// Time patterns
155
def timePatterns = [
156
'HH:mm:ss', // 14:30:45
157
'HH:mm:ss.SSS', // 14:30:45.123
158
'h:mm a', // 2:30 PM
159
'H:mm', // 14:30
160
'HH:mm:ss.SSSSSS', // 14:30:45.123456 (microseconds)
161
]
162
163
def timeString = '14:30:45'
164
timePatterns.each { pattern ->
165
try {
166
def parsed = LocalTime.parse(timeString, pattern)
167
println "${pattern}: ${parsed}"
168
} catch (Exception e) {
169
println "${pattern}: Failed to parse '${timeString}'"
170
}
171
}
172
173
// Timezone patterns
174
def zonePatterns = [
175
'XXX', // +05:30, Z
176
'XX', // +0530, Z
177
'X', // +05, Z
178
'Z', // +0530
179
'z', // EST, GMT
180
'zzzz', // Eastern Standard Time
181
'VV' // America/New_York
182
]
183
```
184
185
### Factory Methods
186
187
Static factory methods for creating temporal objects.
188
189
```groovy { .api }
190
/**
191
* Returns the ZoneOffset currently associated with the system default ZoneId.
192
*/
193
ZoneOffset systemDefault(ZoneOffset type)
194
195
/**
196
* Creates a Period consisting of the number of years between two Year instances.
197
*/
198
Period between(Period type, Year startInclusive, Year endExclusive)
199
200
/**
201
* Creates a Period consisting of the number of years and months between two YearMonth instances.
202
*/
203
Period between(Period type, YearMonth startInclusive, YearMonth endExclusive)
204
```
205
206
**Usage Examples:**
207
208
```groovy
209
import java.time.*
210
211
// System default offset
212
def systemOffset = ZoneOffset.systemDefault()
213
println "System default offset: ${systemOffset}"
214
215
// Period between years
216
def startYear = Year.of(2020)
217
def endYear = Year.of(2024)
218
def yearPeriod = Period.between(startYear, endYear)
219
println "Period between years: ${yearPeriod.years} years"
220
221
// Period between year-months
222
def startYearMonth = YearMonth.of(2024, 1) // January 2024
223
def endYearMonth = YearMonth.of(2024, 7) // July 2024
224
def monthPeriod = Period.between(startYearMonth, endYearMonth)
225
println "Period between year-months: ${monthPeriod.months} months"
226
227
// More complex year-month periods
228
def start = YearMonth.of(2023, 10) // October 2023
229
def end = YearMonth.of(2024, 3) // March 2024
230
def complexPeriod = Period.between(start, end)
231
println "Complex period: ${complexPeriod.years} years, ${complexPeriod.months} months"
232
```
233
234
### Error Handling
235
236
Exception handling for parsing operations.
237
238
**Exceptions Thrown:**
239
240
- `IllegalArgumentException` - If the pattern is invalid
241
- `DateTimeParseException` - If the text cannot be parsed using the pattern
242
243
**Usage Examples:**
244
245
```groovy
246
import java.time.*
247
import java.time.format.DateTimeParseException
248
249
// Handling parse errors
250
def invalidDateString = "2024-13-45" // Invalid month and day
251
def validPattern = "yyyy-MM-dd"
252
253
try {
254
def date = LocalDate.parse(invalidDateString, validPattern)
255
println "Parsed: ${date}"
256
} catch (DateTimeParseException e) {
257
println "Parse error: ${e.message}"
258
println "Error at index: ${e.errorIndex}"
259
println "Parsed text: '${e.parsedString}'"
260
}
261
262
// Pattern validation
263
def invalidPattern = "invalid-pattern"
264
def validDateString = "2024-12-25"
265
266
try {
267
def date = LocalDate.parse(validDateString, invalidPattern)
268
println "Parsed: ${date}"
269
} catch (IllegalArgumentException e) {
270
println "Invalid pattern: ${e.message}"
271
}
272
273
// Helper method for safe parsing
274
def safeParse = { String text, String pattern ->
275
try {
276
return LocalDate.parse(text, pattern)
277
} catch (DateTimeParseException | IllegalArgumentException e) {
278
println "Failed to parse '${text}' with pattern '${pattern}': ${e.message}"
279
return null
280
}
281
}
282
283
// Test safe parsing
284
def result1 = safeParse("2024-12-25", "yyyy-MM-dd") // Success
285
def result2 = safeParse("invalid", "yyyy-MM-dd") // Failure
286
def result3 = safeParse("2024-12-25", "invalid") // Failure
287
288
println "Results: ${result1}, ${result2}, ${result3}"
289
```
290
291
### Advanced Parsing Scenarios
292
293
Complex parsing scenarios with multiple formats and fallback strategies.
294
295
**Usage Examples:**
296
297
```groovy
298
import java.time.*
299
import java.time.format.DateTimeParseException
300
301
// Multi-format parsing helper
302
def parseWithMultipleFormats = { String text, List<String> patterns ->
303
for (pattern in patterns) {
304
try {
305
return LocalDate.parse(text, pattern)
306
} catch (DateTimeParseException e) {
307
// Try next pattern
308
}
309
}
310
throw new DateTimeParseException("Unable to parse '${text}' with any provided pattern", text, 0)
311
}
312
313
// Test with multiple date formats
314
def flexiblePatterns = [
315
'yyyy-MM-dd', // 2024-12-25
316
'dd/MM/yyyy', // 25/12/2024
317
'MMM dd, yyyy', // Dec 25, 2024
318
'dd-MM-yy', // 25-12-24
319
'yyyyMMdd' // 20241225
320
]
321
322
def testDates = [
323
'2024-12-25',
324
'25/12/2024',
325
'Dec 25, 2024',
326
'25-12-24',
327
'20241225',
328
'invalid-date'
329
]
330
331
testDates.each { dateString ->
332
try {
333
def parsed = parseWithMultipleFormats(dateString, flexiblePatterns)
334
println "${dateString} -> ${parsed}"
335
} catch (DateTimeParseException e) {
336
println "${dateString} -> Parse failed"
337
}
338
}
339
340
// Parsing with locale-specific patterns
341
import java.util.Locale
342
343
def parseWithLocale = { String text, String pattern, Locale locale ->
344
def formatter = DateTimeFormatter.ofPattern(pattern, locale)
345
return LocalDate.parse(text, formatter)
346
}
347
348
// Example with different locales (requires proper locale-specific text)
349
def germanDate = parseWithLocale('25. Dezember 2024', 'dd. MMMM yyyy', Locale.GERMAN)
350
def frenchDate = parseWithLocale('25 décembre 2024', 'dd MMMM yyyy', Locale.FRENCH)
351
352
println "German: ${germanDate}"
353
println "French: ${frenchDate}"
354
```
355
356
### Integration with Standard Java Time Parsing
357
358
Integration with existing Java 8 time parsing capabilities.
359
360
**Usage Examples:**
361
362
```groovy
363
import java.time.*
364
import java.time.format.DateTimeFormatter
365
366
// Using predefined formatters with parse extensions
367
def isoDate = LocalDate.parse('2024-12-25', DateTimeFormatter.ISO_LOCAL_DATE.pattern)
368
def isoDateTime = LocalDateTime.parse('2024-12-25T14:30:00', DateTimeFormatter.ISO_LOCAL_DATE_TIME.pattern)
369
370
// Custom formatter reuse
371
def customFormatter = DateTimeFormatter.ofPattern('dd/MM/yyyy HH:mm')
372
def customParsed1 = LocalDateTime.parse('25/12/2024 14:30', customFormatter.pattern)
373
def customParsed2 = LocalDateTime.parse('31/12/2024 23:59', customFormatter.pattern)
374
375
println "Custom parsed: ${customParsed1}, ${customParsed2}"
376
377
// Combining with standard parsing
378
def standardParsed = LocalDate.parse('2024-12-25') // Uses ISO format by default
379
def extensionParsed = LocalDate.parse('25-12-2024', 'dd-MM-yyyy') // Uses extension method
380
381
println "Standard: ${standardParsed}, Extension: ${extensionParsed}"
382
```