我想创建一个跟踪任务时间的ASP.NET WinForms应用程序。我需要能够编写表单,以便我可以将任务添加到数据库,在新选项卡中打开它,并能够启动,暂停和停止任务。当我完成后,我需要计算完成任务所需的时间。我希望看到秒表在页面上运行,显示小时:min:秒通过AJAX每秒更新一次。我已经在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;
}
}
}
答案 0 :(得分:2)
我不确定这是否会导致您的问题,但您应该使用int
代替double
,因为TimeSpan
成员仍为int
。将双精度值与精确数字can cause problems进行比较
int hours = ts_timeElapsed.Hours;
int mins = ts_timeElapsed.Minutes;
int secs = ts_timeElapsed.Seconds;