字符串格式错误
本文关键字:错误 格式 字符串 | 更新日期: 2023-09-27 18:27:58
我已经为我的应用程序编码了正常运行时间,它只是显示随机数字?
程序时间是这个代码
public static DateTime TimeStarted { get; set; }
public static void Time(string[] args)
{
//set start time
Program.TimeStarted = DateTime.Now;
}
然后这是一个显示正常运行时间的类
case "uptime":
{
TimeSpan sinceStarted = (TimeSpan)(DateTime.Now - Program.TimeStarted);
double secondsRunning = sinceStarted.TotalSeconds;
string message = string.Format("{0} Days, {1} hours, and {2} minutes", sinceStarted.Days, sinceStarted.Hours, sinceStarted.Minutes);
Session.SendData(UserAlertModernComposer.Compose("Stats", message));
return true;
}
目前的说法是735096天7小时34分钟,正常运行时间约为20分钟,
没有必要为自己保留这个值。它已在Process.StartTime属性中可用。您只需要获得当前进程的句柄
Process p = Process.GetCurrentProcess();
TimeSpan sinceStarted = (TimeSpan)(DateTime.Now - p.StartTime);
string message = string.Format("{0} Days, {1} hours, and {2} minutes",
sinceStarted.Days, sinceStarted.Hours, sinceStarted.Minutes);
考虑将Stopwatch类用于您的目的。它在System.Diagnostics命名空间中,应该更适合您。
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
正如我在评论中提到的,您从未调用过Time方法这意味着TimeStarted将具有DateTime.MinValue。DateTime.Min Value等于01/01/0001 00:00:00
。这就是你所得到的结果。
您需要做的是在program.cs中写入以下行
Program.TimeStarted = DateTime.Now;
Rest is fine