Question

Below is my code. I want to capture the difference between two timestamps at two different button clicks, i.e., i want the "startTime" of btnStartTime_click event to be used in btnEndTime_click event.

    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);

    }
Was it helpful?

Solution 2

Since this concerns a web application, you must store the startTime in a way where it can be restored on a later post back.

Here's a quick sample that should work using 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);
}

Alternatively you could use session state:

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);
}

OTHER TIPS

Just make your startTime outside the local scope:

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);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top