Safely convert a text date to a date

Sometimes you just need to convert a text to a date, here is a function I have created that should do it without generating an error. If the input string is wrong, it will return a blank date.

Following is presuming text date format YYYYMMDD:

Text2Date(TextDate : Text[30]) : Date
IF TextDate = '' THEN
  EXIT(0D);

IF NOT EVALUATE(Year,COPYSTR(TextDate,1,4)) THEN
  EXIT(0D);

IF (Year < 1) OR (Year > 9999) THEN
  EXIT(0D);

IF NOT EVALUATE(Month,COPYSTR(TextDate,5,2)) THEN
  EXIT(0D);

IF (Month < 1) OR (Month > 12) THEN
  EXIT(0D);

IF NOT EVALUATE(Day,COPYSTR(TextDate,7,2)) THEN
  EXIT(0D);

IF (Day < 1) OR (Day > DATE2DMY(CALCDATE('<+1M-1D>',DMY2DATE(1,Month,Year)),1)) THEN
  EXIT(0D);

EXIT(DMY2DATE(Day,Month,Year));

Year, Month and Day are all local integers.

3 thoughts on “Safely convert a text date to a date

  1. Pingback: Safely convert a text date to a date | Pardaan.com

  2. Pingback: Dynamics NAV String->Date | Blog.NoiK.nl

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.