Android Question How to check for a date

Penfound

Active Member
Licensed User
Longtime User
I have a string variable that holds a date on one format or another. How do I test whether the string in the variable is actually a date.

The tmpstart is supposed to contain a date but, if it is empty it does not register a being null, hence the question.

B4X:
If tmpStart = Null Then
Label14.TextColor=Colors.Red
Label14.Text = "Choose Course"
Else
Label14.text = tmpStart
End If

Thanks for looking
Penfound
 

udg

Expert
Licensed User
Longtime User
Hi Penfound,

if you want to validate a date, try regex (there are plenty of ready-made example on the Internet).
Just for your convenience
B4X:
^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
Source: http://stackoverflow.com/questions/15491894/regex-to-validate-date-format-dd-mm-yyyy
There are shorter and simpler ones out there, like
B4X:
^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$   'yyyy-mm-dd format from 01.01.1900 to 31.12.2099
(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)           'dd/mm/yyyy
Or even: https://www.b4x.com/android/forum/t...-a-date-as-an-edittext-view.15745/#post-89559
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
You must explicitly choose a single date format (or let the user choose one). Otherwise you will not be able to correctly parse the date as the same value can match multiple formats.

For example: 01/02/03

You can use this code to validate the date:
B4X:
Sub IsValidDate(s As String) As Boolean
 Try
   DateTime.DateParse(s)
   Return True
 Catch
   Return False
 End Try
End Sub
 
Upvote 0

udg

Expert
Licensed User
Longtime User
Come on, @Erel .. stealing the show to lightweight volunteers who spend hours in the Forum in search for a couple of "likes" more.. it's no nice! :)
eheh, you know I like jocking; often i find it irresistible.

Seriously now. Your solution is like the one posted here, as I mentioned as my last suggestion in post #2 above. But there we read that passing a date like 31/12/2015a made the test pass, judging it a correct date. It was a 2012 post, so should we consider it fixed now?
(I know for sure that at least one community member will reply to this post with a more than justified "try it yourself! ") :D
 
Last edited:
Upvote 0
Top