Hello,
I’m writing a program that uses time as CCYYMMDDhhmm and I would like to check that the date is valid. I have:
// — Validate date —
Var xx As String = yearStr + monthStr + dayStr + hourStr + minuteStr
Try
Var year As Integer = xx.Middle(0, 4).ToInteger
Var month As Integer = xx.Middle(4, 2).ToInteger
Var day As Integer = xx.Middle(6, 2).ToInteger
Var hour As Integer = xx.Middle(8, 2).ToInteger
Var minute As Integer = xx.Middle(10, 2).ToInteger
Var dt As New DateTime(year, month, day, hour, minute)
// If we reach here, the date is valid
MessageBox("Valid date: " + dt.ToString)
Catch e As RuntimeException
// Invalid date
MessageBox(“Invalid date”)
End Try
My problem is that the debugger stops at
Var dt As New DateTime(year, month, day, hour, minute)
The variable shows xx to be as intended (e.g. 202602311202) but dt is NIL. However I don’t understand why it is.
When the debugger stops the RuntimeException variable will hold the exception so you can read the message. The Message will tell you more about what went wrong.
This is occurring because there aren’t 31 days in February. That raises a “Day out of range” exception. You’ll need to validate your data before attempting to create a DateTime object as each field has a valid range.
First, as an aside, please use the code tags when posting code. It will make it easier for us to read and help.
When I try this code, it works exactly as intended. Given the string you posted, an exception is raised (InvalidArgumentException) and the MessageBox appears. (Feb. 31 is not valid.) If I change the string to a valid date like Feb. 27, I get the “valid date” message.
When you said “the debugger stops…”, I think you are seeing it stop at the exception. If you continue stepping, it will drop into the catch block.
You can avoid this by wrapping the statement in a #pragma:
#pragma BreakOnExceptions False
var dt as new DateTime( ... )
#pragma BreakOnExceptions default
...
catch ...
#pragma BreakOnExceptions default
// Invalid Date
...
2 Likes