How to check if string is a valid DateTime Format string in Delphi

Tofig Hasanov picture Tofig Hasanov · Dec 4, 2009 · Viewed 29.2k times · Source

I want user to be able to manually enter format of the datetime fields in the program. I have Tedit component. For example if user enters 'HH:nn', then this is a valid datetime format string and all datetime components should change format property to this, but if he enters 'asd', it is not. Is there a quick way to check this, without writing my own function?

Answer

Toon Krijthe picture Toon Krijthe · Dec 4, 2009

You could use the functions:

TryStrToDate
TryStrToTime
TryStrToDateTime

They try to convert a string to a date/time and if the conversion succeeds, it returns true. So there are no exceptions raised.

You can use the optional TFormatSettings parameter to define your own format.

All functions are defined in SysUtils.

But there are some date/time controls available in the VCL like TDateTimePicker and TMonthCalendar. You can use them also.