You can use tryParse when you need to convert text to a DateTime value without failing when the text is not a valid date or time.
What tryParse returns
The tryParse operator converts a string representation of a date and time to its DateTime equivalent.
- For valid input, it returns the parsed DateTime value.
- For invalid input, it returns
null.
Use tryParse when the input may be incomplete or invalid, such as text entered by a user. Test for null before using the returned value.
Supported date and time forms
tryParse accepts date-only, time-only, combined date-and-time, and specified time-zone forms. When a component is omitted, tryParse supplies it as described below.
| Input form | Example input | How tryParse handles omitted parts |
|---|---|---|
| Date and time | 2008-11-01 19:35:00
|
Uses the supplied date and time. |
| Date only | 2008-11-01
|
Assumes midnight, 12:00. |
| Month and year | 11/2008
|
Assumes the first day of the month. |
| Month and day | 11/01
|
Assumes the current year. |
| Time only | 19:35
|
Assumes the current date. |
| Hour with AM/PM | 7 PM
|
Assumes the current date and zero minutes and seconds. |
A date with a two-digit year is interpreted according to the Calendar.
Time-zone formats
tryParse accepts ISO 8601 input that includes time-zone information.
| Format | Example |
|---|---|
UTC, identified by Z
|
2008-11-01T19:35:00.0000000Z
|
| ISO 8601 with an offset | 2008-11-01T19:35:00.0000000-07:00
|
| RFC 1123 with the GMT designator | Sat, 01 Nov 2008 19:35:00 GMT
|
| Date and time with an offset | 03/01/2009 05:42:00 -5:00
|
Handle invalid input
Invalid text produces null rather than a DateTime value. For example, use tryParse for input such as not a date or an invalid date and handle the null result in the surrounding OCL logic.
Do not rely on omitted year, date, or time components when you need a stable, unambiguous value. For example, a time-only value uses the current date, so its result changes on a different day.
Choose the appropriate conversion
Use tryParse when a failed conversion must result in null. For other conversion operators, see Documentation:OCLOperators Parse, strToDateTime, and strToDate.
