user283907
user283907

Reputation:

Convert WMI Win32_OperatingSystem InstallDate to mm/dd/yyyy format (C# - WPF)

I am wondering how you would convert the date and time from 20100131022308.000000-360.

I've been trying to figure it out for a while now and I can't seem to get anywhere.

I am using C# in a WPF Application.

Upvotes: 8

Views: 7838

Answers (3)

jgauffin
jgauffin

Reputation: 101130

If you need to parse the dates in .NET Standard you can do the following:

public static bool TryParse(string date, out DateTime result)
{
    if (date == null) throw new ArgumentNullException("date");

    try
    {
        var timezonePos = date.IndexOfAny(new[]{'+', '-'});
        var isPlus = date[timezonePos] == '+';
        var timeZoneStr = date.Substring(timezonePos + 1);
        date = date.Substring(0, timezonePos);

        result = DateTime.ParseExact(date, "yyyyMMddHHmmss.ffffff", CultureInfo.InvariantCulture);

        //get utc by removing the timezone adjustment
        var timeZoneMinutes = int.Parse(timeZoneStr);
        result = isPlus
            ? result.AddMinutes(-timeZoneMinutes)
            : result.AddMinutes(timeZoneMinutes);

        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941257

The System.Management.ManagementDateTimeConverter class was made to solve your problem. Use its ToDateTime() method. It properly parses milliseconds and the UTC offset in the string:

  DateTime dt = System.Management.ManagementDateTimeConverter.ToDateTime("20100131022308.000000-360");
  Console.WriteLine(dt);

Output: 1/31/2010 2:23:08 AM

Upvotes: 33

David Morton
David Morton

Reputation: 16505

Ignore everything after the period:

string date = "20100131022308.000000-360";
date = date.Substring(0, date.IndexOf('.'));
DateTime actualDate = DateTime.ParseExact(date, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
Console.WriteLine(actualDate);

It's a pretty straightforward date format.

Upvotes: 6

Related Questions