我想创建一个跟踪任务时间的 ASP.NET WinForms 应用程序。我需要能够编写表单,以便可以将任务添加到数据库中,在新选项卡中打开它,并且能够启动、暂停和停止任务。完成后,我需要计算完成任务所需的时间。我想查看页面上运行的秒表,显示小时:分钟:秒通过 AJAX 每秒更新一次。我已经在 Web 上查看了 TimeSpan、DateTime、StopWatch 等,但我似乎找不到任何适合我的东西。我从一个带有开始和停止按钮的简单表单开始。开始按钮的 _click 事件分配我的 DateTime 变量“startTime = DateTime.Now”,停止按钮的 _click 事件分配我的 DateTime 变量“endTime = DateTime.Now”。然后我使用 TimeSpan ' elapsed' 来计算 TimeSpan 'elapsed = (endTime - startTime)。当我更新标签以显示经过的时间时,我希望只得到已经过去的秒数,但我得到了整个 DateTime 字符串。下面是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
namespace CS_StopWatch
{
public partial class Default : System.Web.UI.Page
{
//public Stopwatch myStopWatch = new Stopwatch();
public DateTime startTime;
public DateTime endTime;
public TimeSpan ts_timeElapsed;
public string s_timeElapsed;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void StartButton_Click(object sender, EventArgs e)
{
//myStopWatch.Start();
startTime = DateTime.Now;
}
protected void StopButton_Click(object sender, EventArgs e)
{
//myStopWatch.Stop();
//ElapsedLabel.Text = "Time Elapsed: " + myStopWatch.Elapsed;
endTime = DateTime.Now;
ts_timeElapsed = (endTime - startTime);
s_timeElapsed = GetElapsedTimeString();
ElapsedLabel.Text = "Time Elapsed: " + s_timeElapsed;
}
public string GetElapsedTimeString()
{
int days = ts_timeElapsed.Days;
double hours = ts_timeElapsed.Hours;
double mins = ts_timeElapsed.Minutes;
double secs = ts_timeElapsed.Seconds;
string x = "";
if (days != 0)
{
x += days.ToString() + ":";
}
if (hours != 0)
{
x += hours.ToString() + ":";
}
if (mins != 0)
{
x += mins.ToString() + ":";
}
if (secs != 0)
{
x += secs.ToString();
}
return x;
}
}
}