从LastBootUpTime返回的奇怪字符串

时间:2019-07-03 16:21:56

标签: c# datetime wmi

我正在使用Win32_OperatingSystemSystem.Management返回一个值(我知道Microsoft.Management.Infrastructure,但我只是在做一些测试)。

这是我的跑步方式:

string bootTime = "";
//Creating a management searcher object
ManagementObjectSearcher mgmtObjSearcher = new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem");
//Collection to hold "results"
ManagementObjectCollection objCollection = mgmtObjSearcher.Get();
foreach (ManagementObject mgmtObject in objCollection)
{
    bootTime = mgmtObject["LastBootUpTime"].ToString();
}

但是当尝试运行Convert.ToDateTime(bootTime).ToString("dd/MM/yyyy hh:mm:ss");时,出现以下错误:

  

System.FormatException:'字符串未被识别为有效字符串   日期时间。”

LastBootUpTime值似乎以20190703085750.500000+060的形式返回,我似乎无法使用Convert.ToDateTime进行转换,也无法使用DateTime.Parse

有人可以伸出援手让我知道我要去哪里了吗?我只想返回LastBootUpTime并转换特定的字符串格式(“ dd / MM / yyyy hh:mm:ss”)。非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:0)

根据ŇɏssaPøngjǣrdenlarp和SonerGönül的评论,这就是我的结论:

string bootTime = "";
//Creating a management searcher object
ManagementObjectSearcher mgmtObjSearcher = new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem");
//Collection to hold "results"
ManagementObjectCollection objCollection = mgmtObjSearcher.Get();
foreach (ManagementObject mgmtObject in objCollection)
{
    bootTime = ManagementDateTimeConverter.ToDateTime(mgmtObject["LastBootUpTime"].ToString()).ToString("dd/MM/yyyy HH:mm:ss");
}