简体   繁体   English

将WMI Win32_OperatingSystem InstallDate转换为mm / dd / yyyy格式(C#-WPF)

[英]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. 我想知道您将如何转换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. 我在WPF应用程序中使用C#。

The System.Management.ManagementDateTimeConverter class was made to solve your problem. 创建System.Management.ManagementDateTimeConverter类来解决您的问题。 Use its ToDateTime() method. 使用其ToDateTime()方法。 It properly parses milliseconds and the UTC offset in the string: 它将正确解析毫秒和字符串中的UTC偏移量:

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

Output: 1/31/2010 2:23:08 AM 输出:2010/1/31上午2:23:08

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. 这是一种非常简单的日期格式。

If you need to parse the dates in .NET Standard you can do the following: 如果需要在.NET Standard中解析日期,则可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM