Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

.net - How to convert a long datetime string to days in C#

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");

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.

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;
     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...