Convert WMI Win32_OperatingSystem InstallDate to mm/dd/yyyy format (C# - WPF)
I am wondering how you would convert the date and time from 201001310开发者_StackOverflow社区22308.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.
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
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:
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;
}
}
精彩评论