问题描述
我需要能够将以下wmi查询返回的长datetime字符串转换为days:
I need to be able to convert into days the long datetime string returned by the following wmi query:
SelectQuery query = new SelectQuery("SELECT * FROM Win32_NetworkLoginProfile");
安全名称为PasswordAge。
PasswordAge数据类型:datetime
The propety name is PasswordAge.PasswordAge Data type: datetime
密码生效的时间长短。该值是从上次更改密码以来经过的秒数来衡量的。
Length of time a password has been in effect. This value is measured from the number of seconds elapsed since the password was last changed.
示例:00000011171549.000000:000
Example: 00000011171549.000000:000
ManagementScope scope = CreateNewManagementScope(computerName);
SelectQuery query = new SelectQuery("SELECT Name, PasswordAge FROM Win32_NetworkLoginProfile WHERE Privileges=2 ");
try
{
using (var searcher = new ManagementObjectSearcher(scope, query))
{
ManagementObjectCollection accounts = searcher.Get();
List<string> accountNames = new List<string>();
foreach (ManagementObject account in accounts)
{
string name = account["Name"].ToString();
string pAge = account["PasswordAge"].ToString();
accountNames.Add(name + " " + pAge);
}
lstAccounts.DataSource = accountNames;
}
}
推荐答案
,解析 string
来创建一个整数
或 long
。从结果中创建一个 TimeSpan
,然后获取该对象的 Days
属性:
First, parse the string
to create an integer
or long
. Create a TimeSpan
from the result, then get the Days
property of that object:
var s = (long)Double.Parse(pAge);
var t = TimeSpan.FromSeconds(s);
Console.WriteLine(t.Days);
请注意, Days
属性是一个整数。它代表 TimeSpan
中的整天的数量。如果您需要更精确,请包括小时数或秒等。
Note that the Days
property is an integer. It represents the number of whole days in the TimeSpan
. If you need to be more precise, include the number of hours as well, or seconds etc.
另请注意,您给出的示例(19521201000230.000000秒)代表约619,000年。我的猜测是,当用户从未更改密码时,这是查询返回的默认值。我提出这一点,因为它比可以由 TimeSpan
(约29,000年)表示的最长时间长,因此这段代码将无法用于默认值价值。
Also note that the example you gave (19521201000230.000000 seconds) represents about 619,000 years. My guess is that this is the default value returned by the query when a user has never changed their password. I'm bringing this up because it's longer than the max period of time that can be represented by a TimeSpan
(about 29,000 years) so this code won't work for the default value.
这篇关于如何将长datetime字符串转换为C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!