How to convert GMT datetime string to local datetime delphi [duplicate] - delphi

How I can convert "02 August 2012 18:53" to DateTime?
when I use StrToDate for convert it occur error 'Invalid Date format'

You can use VarToDateTime (found in the Variants unit), which supports various time formats Delphi's RTL doesn't. (It's based on COM's date support routines like the ones used in various Microsoft products.) I tested with your supplied date, and it indeed converts it to a TDateTime properly. Tested on both Delphi 2007 and XE2.
program Project2;
{$APPTYPE CONSOLE}
{$R *.res}
uses
SysUtils, Variants;
var
DT: TDateTime;
TestDate: String;
begin
TestDate := '02 August 2012 18:53';
try
DT := VarToDateTime(TestDate);
{ TODO -oUser -cConsole Main : Insert code here }
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
Writeln(FormatDateTime('mm/dd/yyyy hh:nn', DT));
Readln;
end.
More info in the current documentation , including another sample of use (link at the bottom of that page).
Note the function in Variants unit use the default user locale. If it is not 'US' the conversion from the above string might fail. In that case you would better call VarDateFromStr directly from activex unit specifying the US locale:
uses
sysutils, activex, comobj;
var
TestDate: String;
DT: TDateTime;
begin
try
TestDate := '02 August 2012 18:53';
OleCheck(VarDateFromStr(WideString(TestDate), $0409, 0, Double(DT)));
Writeln(FormatDateTime('mm/dd/yyyy hh:nn', DT));
Readln;
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.

Related

GetProcAddress fails to run when compiled under Delphi XE6 x64

The following GetProcAddress code fails when compiled under Delphi XE6 x64. It runs fine when compiled under Delphi x86. Could you help to comment what is done wrong ?
program Project11;
{$APPTYPE CONSOLE}
{$R *.res}
uses
SysUtils;
var
Library_OpenGL: LongWord;
function LoadLibrary(lpFileName: pAnsiChar): LongWord; stdcall; external 'kernel32.dll' name 'LoadLibraryA';
function GetProcAddress(hModule: LongWord; lpProcName: pAnsiChar): Pointer; stdcall; external 'kernel32.dll' name 'GetProcAddress';
begin
try
Library_OpenGL := LoadLibrary('opengl32.dll');
Assert(GetProcAddress(Library_OpenGL, 'glEnable') <> nil, 'GetProcAddress(Library_OpenGL, ''glEnable'') = nil');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
ReadLn;
end.
Your translations are wrong. A module handle is pointer sized which explains why your erroneous translations worked on 32 bit but not 64 bit.
To correct, add the Windows unit to your uses clause, remove your declarations of LoadLibrary() and GetProcAddress(), and declare Library_OpenGL as HMODULE (which is 8 bytes in x64):
program Project11;
{$APPTYPE CONSOLE}
{$R *.res}
uses
SysUtils, Windows;
var
Library_OpenGL: HMODULE;
begin
try
Library_OpenGL := LoadLibrary('opengl32.dll');
Assert(GetProcAddress(Library_OpenGL, 'glEnable') <> nil, 'GetProcAddress(Library_OpenGL, ''glEnable'') = nil');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
ReadLn;
end.
As an added benefit you now call the native Unicode LoadLibraryW directly rather than going via the LoadLibraryA adapter with its conversation from ANSI to the system native UTF-16.

how I can convert str to datetime?

How I can convert "02 August 2012 18:53" to DateTime?
when I use StrToDate for convert it occur error 'Invalid Date format'
You can use VarToDateTime (found in the Variants unit), which supports various time formats Delphi's RTL doesn't. (It's based on COM's date support routines like the ones used in various Microsoft products.) I tested with your supplied date, and it indeed converts it to a TDateTime properly. Tested on both Delphi 2007 and XE2.
program Project2;
{$APPTYPE CONSOLE}
{$R *.res}
uses
SysUtils, Variants;
var
DT: TDateTime;
TestDate: String;
begin
TestDate := '02 August 2012 18:53';
try
DT := VarToDateTime(TestDate);
{ TODO -oUser -cConsole Main : Insert code here }
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
Writeln(FormatDateTime('mm/dd/yyyy hh:nn', DT));
Readln;
end.
More info in the current documentation , including another sample of use (link at the bottom of that page).
Note the function in Variants unit use the default user locale. If it is not 'US' the conversion from the above string might fail. In that case you would better call VarDateFromStr directly from activex unit specifying the US locale:
uses
sysutils, activex, comobj;
var
TestDate: String;
DT: TDateTime;
begin
try
TestDate := '02 August 2012 18:53';
OleCheck(VarDateFromStr(WideString(TestDate), $0409, 0, Double(DT)));
Writeln(FormatDateTime('mm/dd/yyyy hh:nn', DT));
Readln;
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.

Save a IXMLDOMDocument3 to xml-file in runtime with Delphi 2007

If I would like to save a IXMLDOMDocument3 in runtime to a file on my harddrive, what is the syntax for that?
E.g. like IXMLDOMDocument3.save('c:\test.xml')
Or is it even possible?
Best regards!
the sample code below demonstrates how to load and save IXMLDomDocument3 XML at runtime. It uses msxml header file from Delphi-2010. IXMLDomDocument3 inherits from IXMLDomDocument and has Save method (as you wrote in your question). If method parameter is a string, then it specifies file name (it creates or replaces target file).
program Project3;
{$APPTYPE CONSOLE}
uses SysUtils, msxml, comObj, activex;
procedure LoadAndSaveXML(LoadFile, SaveFile : string);
var xml : IXMLDOMDocument3;
tn : IXMLDOMElement;
begin
xml := CreateComObject(CLASS_DOMDocument60) as IXMLDOMDocument3;
xml.load(LoadFile);
xml.save(SaveFile);
end;
begin
try
CoInitialize(nil);
try
LoadAndSaveXML('D:\in.xml', 'D:\out.xml');
finally
CoUninitialize();
end;
except
on E: Exception do begin
Writeln(E.ClassName, ': ', E.Message);
readln;
end;
end;
end.

Getting the whole list of classes and objects defined in a unit using RTTI

I want to get the whole list of classes defined in a specific unit
How can I get the list of all instances of those classes, irrespective of where they are created?
First before to answer your question, remember always include your delphi version in questions related to the Rtti.
1) Asumming which you are using a new version of delphi (>=2010) you can get the unit name of a type using the QualifiedName property , from there you must check the IsInstance property to determine if is a class.
Check the next sample.
{$APPTYPE CONSOLE}
{$R *.res}
uses
Rtti,
System.SysUtils;
procedure Test;
Var
t : TRttiType;
//extract the unit name from the QualifiedName property
function GetUnitName(lType: TRttiType): string;
begin
Result := StringReplace(lType.QualifiedName, '.' + lType.Name, '',[rfReplaceAll])
end;
begin
//list all the types of the System.SysUtils unit
for t in TRttiContext.Create.GetTypes do
if SameText('System.SysUtils',GetUnitName(t)) and (t.IsInstance) then
Writeln(t.Name);
end;
begin
try
Test;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
2) The Rtti can't list the instances of the classes. because the Rtti is about type information and not of instances.
Question 1
The following code does what you ask, relying on the new RTTI introduced in Delphi 2010:
program FindClassesDeclaredInUnit;
{$APPTYPE CONSOLE}
uses
SysUtils, Rtti, MyTestUnit in 'MyTestUnit.pas';
procedure ListClassesDeclaredInNamedUnit(const UnitName: string);
var
Context: TRttiContext;
t: TRttiType;
DeclaringUnitName: string;
begin
Context := TRttiContext.Create;
for t in Context.GetTypes do
if t.IsInstance then
begin
DeclaringUnitName := t.AsInstance.DeclaringUnitName;
if SameText(DeclaringUnitName, UnitName) then
Writeln(t.ToString, ' ', DeclaringUnitName);
end;
end;
begin
ListClassesDeclaredInNamedUnit('MyTestUnit');
Readln;
end.
unit MyTestUnit;
interface
type
TClass1 = class
end;
TClass2 = class
end;
implementation
procedure StopLinkerStrippingTheseClasses;
begin
TClass1.Create.Free;
TClass2.Create.Free;
end;
initialization
StopLinkerStrippingTheseClasses;
end.
Question 2
There is no global registry of object instances.

Getting connected USB info with Delphi on Vista

How can I get 'connected usb info'(device instance id, driver key name ..) from Registry in Vista or Windows 7 by using delphi?
Where is this information in Windows Registry?
I have a code it's working on XP but not in Vista.(c++ code: http://www.codeproject.com/KB/system/RemoveDriveByLetter.aspx)
Why the code is not working on Vista?
I'm really stack about that. Please help.
Thanks a lot for your answers.
You can use the WMI class Win32_DiskDrive. if you need get info about the logical drive you can query the wmi with something like this
Select * Win32_LogicalDisk where DriveType = 2
to access the WMI from delphi you must import the Microsoft WMIScripting V1.x Library using Component->Import Component->Import type library->Next->"Select the library"->Next->Add unit to project->Finish.
if you need more info about usb devices you can check also the next classes
Win32_USBControllerDevice
Win32_PnPEntity
See this example (tested in Delphi 2007 and Windows 7)
program GetWMI_USBConnectedInfo;
{$APPTYPE CONSOLE}
uses
Classes,
ActiveX,
Variants,
SysUtils,
WbemScripting_TLB in '..\..\..\Documents\RAD Studio\5.0\Imports\WbemScripting_TLB.pas';
procedure GetUSBDiskDriveInfo;
var
WMIServices : ISWbemServices;
Root : ISWbemObjectSet;
Item : Variant;
i : Integer;
StrDeviceUSBName: String;
begin
WMIServices := CoSWbemLocator.Create.ConnectServer('.', 'root\cimv2','', '', '', '', 0, nil);
Root := WMIServices.ExecQuery('Select * From Win32_DiskDrive Where InterfaceType="USB"','WQL', 0, nil);//more info in http://msdn.microsoft.com/en-us/library/aa394132%28VS.85%29.aspx
for i := 0 to Root.Count - 1 do
begin
Item := Root.ItemIndex(i);
Writeln('Caption '+VarToStr(Item.Caption));
Writeln('DeviceID '+VarToStr(Item.DeviceID));
Writeln('FirmwareRevision '+VarToStr(Item.FirmwareRevision));
Writeln('Manufacturer '+VarToStr(Item.Manufacturer));
Writeln('Model '+VarToStr(Item.Model));
Writeln('PNPDeviceID '+VarToStr(Item.PNPDeviceID));
Writeln('Status '+VarToStr(Item.Status));
End;
end;
begin
try
CoInitialize(nil);
GetUSBDiskDriveInfo;
Readln;
CoUninitialize;
except
on E:Exception do
Begin
CoUninitialize;
Writeln(E.Classname, ': ', E.Message);
Readln;
End;
end;
end.

Resources