Mega Code Archive

 
Categories / Delphi / String
 

String TDateString

Title: String - TDateString Question: Today I was receiving some data in CSV format, the first column was a date in the format d-mmm-yy (1-Jan-99 for example). I needed to put the date into a TDateTime to process it. Well... I turned to strToDate function. Check the documentation and you'll see the severe limitations on the use. I was really angry for not been able to convert a date stored in a string into a TDateTime... man! this is so simple it should've been included into Delphi! So then I had to write my own StringToDate function. Answer: Here it comes. function StringToDate(dt : string) : TDateTime; var i : integer; // Variables to store the resulting date s, del, sx, mf : string; // auxiliary variables sa, sm, sd, tok : string; begin s := ShortDateFormat; sx := s; del := dateSeparator; { First we must get and decode the local format for short dates } for i := 1 to 3 do begin tok := uppercase(getToken(s,del)); case tok[1] of 'Y' : sa := getToken(dt, del); 'M' : begin sm := getToken(dt, del); mf := tok; end; 'D' : sd := getToken(dt, del); end; end; { Now we must determine the month format. } if mf='MMM' then begin for i := 1 to 12 do if uppercase(ShortMonthNames[i])=uppercase(sm) then begin sm := inttostr(i); break; end; end else if mf='MMMM' then begin for i := 1 to 12 do if uppercase(LongMonthNames[i])=uppercase(sm) then begin sm := inttostr(i); break; end; end; { Then we can use the strToDate() and it'll do what it should've done! } dateSeparator := '/'; ShortDateFormat := 'YYYY/MM/DD'; Result := strToDate(sa+'/'+sm+'/'+sd); dateSeparator := del[1]; ShortDateFormat := sx; end; Tomorrow I'll append more documentation. As you can see, this function uses two of the global variables, dateSeparator which will store the separator for the dates, and the shortDateFormat var. Here's an example on how I used it: x := '2-Jan-01'; // Remember, this came from a file ShortDateFormat := 'd-mmm-yy'; dateSeparator := '-'; theDate := StringToDate(x); Note: This function uses the other function I posted earlier: getToken, you can find it in Delphi3000's article number 1787