Is there a way to test if a string Datetime is ok instead of getting error msg?

Is there a way to test if a string Datetime is ok instead of getting error msg?

james_rodgers1
Not applicable
11 Views
2 Replies
Message 1 of 3

Is there a way to test if a string Datetime is ok instead of getting error msg?

james_rodgers1
Not applicable

[ FlexSim 23.0.3 ]

I am obtaining a date in string format and converting it to a Datetime. But if it fails, I get an error message. I would prefer to be able to test it first and create a "soft" error message for the user.

DateTime(date_string,"%m-%d-%Y %H:%M"); is what I'm using where "date_string" is the value read in from the table. I want to be able to test if this will be successful without incurring an error message.

0 Likes
Accepted solutions (1)
12 Views
2 Replies
Replies (2)
Message 2 of 3

Matthew_Gillespie
Autodesk
Autodesk
Accepted solution

You could use a regular expression to check that the string is in the right format before you pass it in to the DateTime. For example:

string dateString = "10-21-1988 08:34";
return dateString.match(/([1-9]|1[0-2])-([1-9]|[12][0-9]|3[0-2])-([12]\d{3}) ([01][0-9]|2[0-4]):([0-5][0-9])/).length;

That might look scary, but I can explain what it's doing. First it says the string should start with a number that's either a single number 1-9 or a 2 digit number that starts with 1 and ends with 0-2 (a number between 1 and 12 in other words). Then there should be a dash. Then there should be a number between 1 and 31. Then a dash. Then a 1 or a 2 followed by 3 more numbers. Then a space. Then a 2 digit number 00-24. Then a 2 digit number 00-59.

You could also do a more simplistic regex like this:

return dateString.match(/\d{2}-\d{2}-\d{4} \d{2}:\d{2}/).length;

So you're just looking for 2 numbers - 2 numbers - 4 numbers space 2 numbers colon 2 numbers



Matthew Gillespie
FlexSim Software Developer

0 Likes
Message 3 of 3

james_rodgers1
Not applicable
Perfect!!! Thanks Matthew.
0 Likes