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

3

7

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.

Blockbusting answered 1/3, 2010 at 20:55 Comment(0)
M
32

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

Municipal answered 2/3, 2010 at 3:6 Comment(1)
Thank you for ending my 3 hours internet searching for this function :) i didnt think about looking in that namespace for a date time converterKeene
H
6

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.

Hanks answered 1/3, 2010 at 21:4 Comment(0)
H
0

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;
    }
}
Hagiographer answered 18/3, 2018 at 11:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.