Tuesday, June 19, 2012

Crystal Reports String to Date Conversion

So, I have gotten this question a lot lately regarding Crystal Reports and converting strings to dates. Conversion from date to string is relatively easy--ToText(command.your_item, 'dd-MM-yyyy') usually does the trick, but a lot of confusion happens when converting in the other direction.

Those date functions you see up in your Crystal Reports function? Ya... those aren't really going to help you much... You are going to have to write your OWN formula. How? By simple counting. In my example, string_date looks something like this: "05/07/2012 05:05.0606" in other words MM/DD/YYYY mm:HH.ssss.' The first step, is to write out your string so you can see what you are working with. Then assign variables to each section of your string. To grab the year, I could count either 4 places from the 6th position of the string or add 2000 to the last 2 positions in the string beginning at place 9. It alls comes back to counting. Remember that empty spaces in your string count as a position, as do '/' or '-' symbols.

year=2000+2 places after the 9th position
month=the first 2 numbers
day=2 places beginning on the 4 position
... and so on
This is the formula I use--feel free to copy/paste/modify until you get the hang of it. Naturally, depending on what your string looks like, the numbers used for position by tonumber() may vary  ;)

numbervar y := 2000 + tonumber(mid({Command.string_date},9,2));
numbervar m := tonumber(mid({Command.string_date},1,2));
numbervar d := tonumber(mid({Command.string_date},4,2));
numbervar h := tonumber(mid({Command.string_date},12,2));
numbervar n := tonumber(mid({Command.string_date},15,2));
numbervar s := tonumber(mid({Command.string_date},18,2));

//datetime(y,m,d,h,s)

date(Y,M,D)