我在将字符串转换为日期和时间时遇到问题。我知道我需要截断字符串,但我似乎无法找到有关如何执行此操作的任何信息。我想其他人也会有这个问题,所以我想我会把它放在这里用于研究目的。这是代码:
uses
SysUtils,
ActiveX,
ComObj,
Variants;
procedure GetLogEvents;
const
wbemFlagForwardOnly = $00000020;
var
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
EventDate : TDateTime;
begin;
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
FWbemObjectSet:= FWMIService.ExecQuery(
'SELECT SourceName,TimeGenerated,ComputerName,EventCode,Message,RecordNumber ' +
' FROM Win32_NTLogEvent ' +
'WHERE Logfile="Application"','WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
while oEnum.Next(1, FWbemObject, iValue) = 0 do
begin
if not VarIsNull(FWbemObject.SourceName)
then Writeln(Format('SourceName %s',[String(FWbemObject.SourceName)]));
if not VarIsNull(FWbemObject.TimeGenerated)
then Writeln(StrToDateTime(FWbemObject.TimeGenerated));
我收到错误:
EConvertError:'20140307135950.000000-000'不是有效的日期和时间。
有人可以告诉我如何解决这个问题吗?
答案 0 :(得分:1)
处理WMI日期时间(公共信息模型日期时间值)的正确方法是使用WbemScripting.SWbemDateTime
对象。
试试这个样本
uses
SysUtils,
ActiveX,
ComObj,
Variants;
function WmiDateToTDatetime(vDate : OleVariant) : TDateTime;
var
FWbemDateObj : OleVariant;
begin;
FWbemDateObj := CreateOleObject('WbemScripting.SWbemDateTime');
FWbemDateObj.Value:=vDate;
Result:=FWbemDateObj.GetVarDate;
end;
procedure GetLogEvents;
const
wbemFlagForwardOnly = $00000020;
var
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
EventDate : TDateTime;
begin;
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
FWbemObjectSet:= FWMIService.ExecQuery(
'SELECT SourceName,TimeGenerated,ComputerName,EventCode,Message,RecordNumber ' +
' FROM Win32_NTLogEvent ' +
'WHERE Logfile="Application"','WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
while oEnum.Next(1, FWbemObject, iValue) = 0 do
begin
if not VarIsNull(FWbemObject.SourceName)
then Writeln(Format('SourceName %s',[String(FWbemObject.SourceName)]));
if not VarIsNull(FWbemObject.TimeGenerated)
then Writeln(DateTimeToStr(WmiDateToTDatetime(FWbemObject.TimeGenerated)));
FWbemObject:=Unassigned;
end;
end;
begin
try
CoInitialize(nil);
try
GetLogEvents;
finally
CoUninitialize;
end;
except
on E:EOleException do
Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.