下面是我的代码。我想在两次不同的按钮点击时捕捉两个时间戳之间的差异,即,我希望在btEndTime_click事件中使用btnStartTime_clickEvent的"startTime"。
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
lblStartTime.Text = startTime.ToString("HH:mm:ss tt");
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is "+workDuration);
}
只需将您的startTime
置于本地范围之外即可:
DateTime startTime;
protected void btnStartTime_Click(object sender, EventArgs e)
{
startTime = DateTime.Now;
lblStartTime.Text = startTime.ToString("HH:mm:ss tt");
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is "+workDuration);
}
由于这涉及到一个web应用程序,您必须以一种可以在以后的发布中恢复startTime
的方式来存储它。
下面是一个应该使用ViewState
:的快速示例
private const string StartTimeViewstateKey = "StartTimeViewstateKey";
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
ViewState[StartTimeViewstateKey] = startTime.ToString(CultureInfo.InvariantCulture);
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Parse((string)ViewState[StartTimeViewstateKey], CultureInfo.InvariantCulture);
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is " + workDuration);
}
或者,您可以使用会话状态:
private const string StartTimeSessionKey= "StartTimeSessionKey";
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
Session[StartTimeSessionKey] = startTime;
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var startTime = (DateTime)Session[StartTimeSessionKey];
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is " + workDuration);
}