Jon*_*aub 3 c# datetime uptime
我想返回一个字符串,这在语法上是正确的,以显示当前的正常运行时间.例如,3年,7个月,11天,1小时,16分钟和零秒,意味着单数单位不应该是复数,零单位应该是复数,但如果尚未出现则不应显示零(例如,如果尚未显示年份,月份等,则不显示)
由于ticks方法不会超过一个月,我使用ManagementObject,但我对如何进行日期时间计算和分解感到困惑(我对C#很新,所以我正在创建一个实现各种功能的实用程序所以我可以学习各种各样的东西.
这就是我现在所拥有的,而且不是很多......
任何帮助是极大的赞赏.
public string getUptime()
{
// this should be grammatically correct, meaning, 0 and greater than 1 should be plural, one should be singular
// if it can count in realtime, all the better
// in rare case, clipping can occur if the uptime is really, really huge
// you need a function that stores the boot time in a global variable so it's executed once so repainting this won't slow things down with quer
SelectQuery query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject mo in searcher.Get())
{
// this is the start time, do math to figure it out now, hoss
DateTime boot = ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
// or is it better to break up everything into days/hours/etc, i think its better to do that at the end before it gets returned
}
string now = DateTime.Now.ToShortDateString();
return "3 years, 7 months, 11 days, 1 hour, 16 minutes and zero seconds"; // long string for testing label width
}
Run Code Online (Sandbox Code Playgroud)
不要'转换为字符串 - 使用DateTime您已经拥有的上次重启时间并将其与当前时间(DateTime.Now)进行比较.减去这两个,你得到一个TimeSpan:
TimeSpan upDuration = DateTime.Now - boot;
Run Code Online (Sandbox Code Playgroud)
TimeSpan 具有属性Days,Hours,Minutes,您现在可以使用这些属性来构建字符串.