We help IT Professionals succeed at work.

Converting from String to DateTime when format contains text

blitz051697
blitz051697 asked
on
Medium Priority
503 Views
Last Modified: 2010-04-06
I noticed that if the regional settings for a date contain strings (i.e dd-mmm-yy will result in 03-OCT-01) I can not use the StrToDate functions to convert to a TDateTime.

Can I convert these types using these routines?  AM I missing something.  

Bottom line :

IF the user enters : 03-OCT-01, I want to convert to a datetime.
Comment
Watch Question

Commented:
Hi

Try this:

var
 DateValue : DateTime;
 DateTimeValue : DateTime;
begin
  DateValue := StrToDateTime(Edit1.Text);
  DateTimeValue := FormatDateTime('dd-MMM-yyyy hh:mm AM/PM', DateValue);
  Label1.Caption := DateTimeToStr(DateTimeValue);
end;


This should convert the date '01-OCT-01 10:22 AM'

Hope this assists

Regards
TAZI
The DateTime problems has been discussed here before.
You can follow link below if you wan't to see the whole discussion.

http://www.experts-exchange.com/jsp/qShow.jsp?ta=delphi&qid=20184702

If you want to check the Regional settings, here's how (only tested on NT4)

You must include Registry in the uses section

var
  Reg : TRegistry
  DateFormat : String;

  Reg:=TRegistry.Create;
  Reg.RootKey:=HKEY_CURRENT_USER;
  if Reg.OpenKeyReadOnly('Control Panel\International') then
    DateFormat:=Reg.ReadString('sShortDate');
  else
    ShowMessage('Reg Key not found "');
  Reg.CloseKey;
  Reg.Free;
  // you can now use the format on the current PC to format the desired date

  DateStr:= FormatDateTime(DateFormat, Now);

Author

Commented:
DelRunner, you missed my point.  I need to convert from a string to a datetime.  
If the user enters 03-OCT-2001 in a text field, I want convert to a TDateTime.  Not vice versa.  The problem seems to be that the StrToDateTime does not like formats that contain strings such as OCT or October.  
CERTIFIED EXPERT

Commented:
Hi,
Not an elegant solution but it's working:

function Str2Date(TheDate: string) : TDateTime;
var
  sDate,sMonth: string;
  i: integer;
begin
  sDate := TheDate;
  // get the Short Month Name
  sMonth := AnsiUpperCase(Copy(sDate,Pos(DateSeparator ,sDate) + 1,3));
  // search for matching
  for i := 1 to 12 do begin
    if sMonth = Copy(AnsiUpperCase(ShortMonthNames[i]),1,3) then begin
      sDate := Copy(sDate,1,3) + IntToStr(i) + Copy(sDate, 7, Length(sDate) - 6);
      break;
    end;
  end;
  result := StrToDate(sDate);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  TheDate: TDateTime;
begin
  TheDate := Str2Date(Edit1.Text);
  ShowMessage(DateToStr(TheDate));
end;

Regards, Geo

Commented:
Hi blitz!

I wrote a small function for you to convert a string in a special format into TDate. Here it is:

function StrToDateSpecial(S: string): TDate;
var
 D, M, Y: Word;

  function StripToChar(var S: string; Ch: char): string;
  var
    Temp: Integer;
  begin
    Result := '';
    Temp := Pos(Ch, S);
    if Temp > 0 then
    begin
      Result := Copy(S, 1, Temp - 1);
      Delete(S, 1, Temp);
    end;
  end;

  function MonthNameToNumber(const S: string): Word;
  var
    I: Word;
  begin
    Result := 0;
    for I := Low(ShortMonthNames) to High(ShortMonthNames) do
    if ShortMonthNames[I] = AnsiUppercase(S) then
    begin
      Result := I;
      Break;
    end;
  end;

begin
  D := StrToInt(StripToChar(S, '-'));
  M := MonthNameToNumber(StripToChar(S, '-'));
  Y := StrToInt(S);
  Result := EncodeDate(Y, M, D);
end;

I have typed the source directly into browser since I don't have a possibility to test it now so it may contain syntax errors...


Hope this helps, Ivo.

Commented:
The following code will parse dates like:
31-Sep-2001
31-September-2001
31 Sept 01
Sept-31 2001
12/sept/2001
12/09/2001

Use it like this:
  try
    ChosenDate := DateFromString(Edit1.Text);
  except
    Messagedlg('Please enter a valid date',mtError,[mbok],0);
  end;

or like this:
  try
    ChosenDate := DateFromString(Edit1.Text,dlDMY);
  except
    Messagedlg('Please enter a valid date in d-m-yyyy format',mtError,[mbok],0);
  end;  


//----------------- BOF code snippet ----------------------

type
  DateLayout = (dlUnknown, dlMDY, dlDMY, dlYMDymd, dlYDM);

function DateFromString(const sDate: string; const layout: DateLayout = dlUnknown): TDateTime;
type
  digits = '0'..'9';
  chars = 'A'..'z';

const
  months: array[1..12] of string = ('January','February','March','April','May','June','July','August','September','October','November','December');

  function IsWordChar(const ch: char): boolean;
  begin
    result := (ch in digits) or (ch in chars);
  end;

  function GetMonth(sMonth: string): Word;
  var
    m, mL: integer;
  begin
    //I'm assuming Delphi's EncodeDateTime function expects January to be
    //month 1 (not 0). If this ain't the case, change to the line "result := m" to "result := m-1"
    sMonth := Lowercase(sMonth);
    result := -1;
    mL := Length(sMonth);
    for m := 1 to 12 do
    begin
      if Lowercase(Copy(months[m],1,mL)) = Lowercase(sMonth) then
      begin
        result := m;
        break;
      end;
    end;
  end;

var
  i, L: integer;
  s: string;
  parts: array[1..3] of string;
  y, m, d: Word;
begin
  i := 1;
  s := '';
  d := -1;
  m := -1;
  y := -1;
  L := Length(sDate);
  while (i < L) and (not IsWordChar(sDate[i])) do
    inc(i);
  while (i < L) and IsWordChar(sDate[i]) do
  begin
    s := s + sDate[i];
    inc(i);
  end;
  parts[1] := s;
  s := '';
  while (i < L) and (not IsWordChar(sDate[i])) do
    inc(i);
  while (i < L) and IsWordChar(sDate[i]) do
  begin
    s := s + sDate[i];
    inc(i);
  end;
  parts[2] := s;
  s := '';
  while (i < L) and (not IsWordChar(sDate[i])) do
    inc(i);
  while (i < L) and IsWordChar(sDate[i]) do
  begin
    s := s + sDate[i];
    inc(i);
  end;
  parts[3] := s;
  s := '';
 
  case layout of
    dlDMY:
      begin
        d := StrToInt(parts[1]);
        try
          m := StrToInt(parts[2]);
        except
          m := GetMonth(parts[2]);
        end;
        y := StrToInt(parts[3]);
      end;
    dlMDY:
      begin
        d := StrToInt(parts[2]);
        try
          m := StrToInt(parts[1]);
        except
          m := GetMonth(parts[1]);
        end;
        y := StrToInt(parts[3]);
      end;
    dlYMD:
      begin
        d := StrToInt(parts[3]);
        try
          m := StrToInt(parts[2]);
        except
          m := GetMonth(parts[2]);
        end;
        y := StrToInt(parts[1]);
      end;
    dlYDM:
      begin
        d := StrToInt(parts[2]);
        try
          m := StrToInt(parts[3]);
        except
          m := GetMonth(parts[3]);
        end;
        y := StrToInt(parts[1]);
      end;
    dlUnknown:
      begin
        try
          m := StrToInt(parts[1]);
        except
          m := GetMonth(parts[1]);
        end;
        if m < 0 then
        begin
          try
            m := StrToInt(parts[2]);
          except
            m := GetMonth(parts[2]);
          end;
          if m < 0 then
          begin
            try
              m := StrToInt(parts[3]);
            except
              m := GetMonth(parts[3]);
            end;
            if m > 0 then
            begin
              d := StrToInt(parts[1]);
              y := StrToInt(parts[2]);
            end;
          end
          else
          begin
            d := StrToInt(parts[1]);
            y := StrToInt(parts[3]);
          end;
        end
        else
        begin
          d := StrToInt(parts[2]);
          y := StrToInt(parts[3]);
        end;
        if d > 31 then
        begin
          L := y;
          y := d;
          d := L;
        end;
      end;
  end;

  if y < 2000 then y := y + 2000;
  if m < 0 then raise Exception.Create("Invalid date format");
  result := EncodeDate(y,m,d);
end;

//----------------- EOF code snippet ----------------------

rondi.

Author

Commented:
Ok, the solution must work off of all possible regional date settings.  IF you bring up the regional settings you will see that you can specify just about any combination of date formats.

Author

Commented:
Ok here is what I really want.  I want one method that will take a string representing a date (or date/time) entered by the user and will convert it to a TDateTime.  The expected imput from the user will always match the date and time from the regional settings.  

For example if the regional settings are dd-mmm-yyyy then the user must specify '01-Oct-2001' as input.  Also, the user may also specify the time portion as well and it should also match the regional settings as well.  If they enter '01-OCt-2001 12:00 AM'-- that should work.
CERTIFIED EXPERT

Commented:
Hi,
Why don't you use two TDateTimePicker components, one for the date and the other for time, and read their Date and Time properties? I think that it would be much easier to implement and it would do exactly what you want.

Regards ,Geo

Author

Commented:
Hi geobul,
That would make sense.    But my comment about user input was only intended to give a clear pic to someone and I didnt want to get into. In realty these strings that I am trying to work with are not input by the user.  Instead I have them in a listview and I am trying to sort on them.  This wasnt code that I wrote (I would have just stored the date) and I am only maintaining it and I am trying to avoid rewriting the whole thing.  If I could just modify the custom sort routine to correctly convert the string to a TDAtetime then I can move on to something else.

One of your questions is current, but the others are not and need your attention.  ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if they are still open in 14 days.  Experts, please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.20149160.html
http://www.experts-exchange.com/questions/Q.20190075.html
http://www.experts-exchange.com/questions/Q.20256401.html
http://www.experts-exchange.com/questions/Q.20290655.html



*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations.
If you are interested in the cleanup effort, please click this link
http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643 
POINTS FOR EXPERTS awaiting comments are listed in the link below
http://www.experts-exchange.com/commspt/Q.20277028.html
 
Moderators will finalize this question if in @14 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thanks everyone.
Moondancer
Moderator @ Experts Exchange
Zero response to my request by anyone.  125 points refunded, question moved to our PAQ/closed.
Moondancer - EE Moderator