0
# String Parsing
1
2
Safe string parsing capabilities with Option-based returns and custom format support for all major date/time types. Provides both exception-throwing and safe parsing methods with comprehensive format support.
3
4
## Capabilities
5
6
### Enhanced String Class
7
8
Rich wrapper providing comprehensive date/time parsing functionality for strings.
9
10
```scala { .api }
11
/**
12
* Adds date/time parsing methods to strings
13
* @param s The underlying string value
14
*/
15
implicit class RichString(val s: String) extends AnyVal {
16
// Direct parsing methods (throws exceptions on invalid input)
17
def toDateTime: DateTime
18
def toInterval: Interval
19
def toLocalDate: LocalDate
20
21
// Safe parsing methods (returns Option)
22
def toDateTimeOption: Option[DateTime]
23
def toLocalDateOption: Option[LocalDate]
24
def toIntervalOption: Option[Interval]
25
26
// Parsing with custom formats (throws exceptions on invalid input)
27
def toDateTime(format: String): DateTime
28
def toLocalDate(format: String): LocalDate
29
30
// Safe parsing with custom formats (returns Option)
31
def toDateTimeOption(format: String): Option[DateTime]
32
def toLocalDateOption(format: String): Option[LocalDate]
33
34
// DateTimeFormat-based parsing
35
def dateTimeFormat(format: String): DateTime
36
def localDateTimeFormat(format: String): LocalDate
37
}
38
```
39
40
**Usage Examples:**
41
42
```scala
43
import com.github.nscala_time.time.Imports._
44
45
// Direct parsing (throws exceptions for invalid input)
46
val dateTime1 = "2023-12-25T10:30:00".toDateTime
47
val localDate1 = "2023-12-25".toLocalDate
48
val interval1 = "2023-01-01T00:00:00/2023-12-31T23:59:59".toInterval
49
50
// Safe parsing (returns Option)
51
val safeParsing1 = "2023-12-25T10:30:00".toDateTimeOption
52
val safeParsing2 = "invalid-date".toDateTimeOption // Returns None
53
val safeParsing3 = "2023-12-25".toLocalDateOption
54
55
safeParsing1 match {
56
case Some(dt) => println(s"Parsed successfully: $dt")
57
case None => println("Failed to parse")
58
}
59
60
// Custom format parsing
61
val customDate1 = "25/12/2023".toDateTime("dd/MM/yyyy")
62
val customDate2 = "Dec 25, 2023".toLocalDate("MMM dd, yyyy")
63
64
// Safe custom format parsing
65
val safeCustom1 = "25/12/2023".toDateTimeOption("dd/MM/yyyy")
66
val safeCustom2 = "invalid".toDateTimeOption("dd/MM/yyyy") // Returns None
67
68
// Using DateTimeFormat patterns
69
val formatted1 = "2023-12-25T10:30".dateTimeFormat("yyyy-MM-dd'T'HH:mm")
70
val formatted2 = "25-Dec-2023".localDateTimeFormat("dd-MMM-yyyy")
71
```
72
73
### Safe Option-Based Parsing
74
75
The library provides safe parsing methods that return `Option` types to handle invalid input gracefully.
76
77
```scala { .api }
78
/**
79
* Safe parsing implementation that catches IllegalArgumentException
80
* and returns None for invalid input
81
*/
82
private def toOption[A](f: => A): Option[A] = try {
83
Some(f)
84
} catch {
85
case _: IllegalArgumentException => None
86
}
87
```
88
89
**Safe Parsing Examples:**
90
91
```scala
92
import com.github.nscala_time.time.Imports._
93
94
// Handling multiple date formats safely
95
val dateStrings = List(
96
"2023-12-25T10:30:00",
97
"invalid-date",
98
"2023-12-25",
99
"not-a-date-at-all"
100
)
101
102
val parsedDates = dateStrings.map(_.toDateTimeOption)
103
// Result: List(Some(DateTime), None, Some(DateTime), None)
104
105
val validDates = parsedDates.flatten
106
// Result: List(DateTime, DateTime) - only valid dates
107
108
// Pattern matching for safe parsing
109
def parseAndHandle(dateStr: String): String = {
110
dateStr.toDateTimeOption match {
111
case Some(dt) => s"Successfully parsed: ${dt.toString("yyyy-MM-dd")}"
112
case None => s"Failed to parse: $dateStr"
113
}
114
}
115
116
// Custom format safe parsing
117
val customFormats = List(
118
("25/12/2023", "dd/MM/yyyy"),
119
("2023-12-25", "yyyy-MM-dd"),
120
("invalid", "dd/MM/yyyy")
121
)
122
123
val customResults = customFormats.map { case (date, format) =>
124
date.toDateTimeOption(format)
125
}
126
// Result: List(Some(DateTime), Some(DateTime), None)
127
```
128
129
### Common Date Format Patterns
130
131
Examples of commonly used date format patterns for parsing.
132
133
**ISO Date Formats:**
134
```scala
135
// Standard ISO formats (parsed automatically)
136
"2023-12-25T10:30:00".toDateTime // ISO DateTime
137
"2023-12-25T10:30:00.123Z".toDateTime // ISO with milliseconds and UTC
138
"2023-12-25T10:30:00+01:00".toDateTime // ISO with timezone offset
139
"2023-12-25".toLocalDate // ISO Date
140
```
141
142
**Custom Format Examples:**
143
```scala
144
// US date formats
145
"12/25/2023".toDateTime("MM/dd/yyyy")
146
"Dec 25, 2023".toLocalDate("MMM dd, yyyy")
147
"December 25, 2023".toLocalDate("MMMM dd, yyyy")
148
149
// European date formats
150
"25/12/2023".toDateTime("dd/MM/yyyy")
151
"25.12.2023".toLocalDate("dd.MM.yyyy")
152
"25-Dec-2023".toLocalDate("dd-MMM-yyyy")
153
154
// Time formats
155
"10:30:45".toLocalTime // ISO time format (if LocalTime parsing available)
156
"10:30 AM".toTime("hh:mm aa") // 12-hour format with AM/PM
157
158
// Combined date-time formats
159
"25/12/2023 10:30".toDateTime("dd/MM/yyyy HH:mm")
160
"Dec 25, 2023 at 10:30 AM".toDateTime("MMM dd, yyyy 'at' hh:mm aa")
161
```
162
163
### Interval Parsing
164
165
String parsing support for Joda Time intervals.
166
167
```scala
168
import com.github.nscala_time.time.Imports._
169
170
// ISO interval formats
171
val interval1 = "2023-01-01T00:00:00/2023-12-31T23:59:59".toInterval
172
val interval2 = "2023-01-01/P1Y".toInterval // Start date + period
173
val interval3 = "P1Y/2023-12-31".toInterval // Period + end date
174
175
// Safe interval parsing
176
val safeInterval1 = "2023-01-01T00:00:00/2023-12-31T23:59:59".toIntervalOption
177
val safeInterval2 = "invalid-interval".toIntervalOption // Returns None
178
179
// Working with parsed intervals
180
safeInterval1.foreach { interval =>
181
println(s"Duration: ${interval.toDurationMillis} ms")
182
println(s"Start: ${interval.getStart}")
183
println(s"End: ${interval.getEnd}")
184
}
185
```
186
187
### Error Handling Best Practices
188
189
Recommended patterns for handling parsing errors.
190
191
```scala
192
import com.github.nscala_time.time.Imports._
193
194
// Using for-comprehensions with Option
195
def parseUserInput(date: String, time: String): Option[DateTime] = {
196
for {
197
parsedDate <- date.toLocalDateOption
198
parsedDateTime <- s"${parsedDate}T${time}".toDateTimeOption
199
} yield parsedDateTime
200
}
201
202
// Using Try for more detailed error handling
203
import scala.util.Try
204
205
def parseWithTry(dateStr: String): Try[DateTime] = {
206
Try(dateStr.toDateTime)
207
}
208
209
// Providing default values
210
def parseWithDefault(dateStr: String, default: DateTime): DateTime = {
211
dateStr.toDateTimeOption.getOrElse(default)
212
}
213
214
// Multiple format attempts
215
def parseMultipleFormats(dateStr: String): Option[DateTime] = {
216
val formats = List("yyyy-MM-dd", "dd/MM/yyyy", "MM/dd/yyyy")
217
218
formats.view
219
.map(format => dateStr.toDateTimeOption(format))
220
.find(_.isDefined)
221
.flatten
222
}
223
```