Reputation: 117
Hello I'm trying to make a stopwatch. I've used a code from the internet to count the minutes and seconds: This is the code( works fine)
public partial class Ingelogd2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sw = new Stopwatch();
sw.Start();
}
}
private static Stopwatch sw;
protected void tm1_Tick(object sender, EventArgs e)
{
long sec = sw.Elapsed.Seconds;
long min = sw.Elapsed.Minutes;
if (min < 60)
{
if (min < 10)
Henkie.Text = "0" + min;
else
Henkie.Text = min.ToString();
Henkie.Text += " : ";
if (sec < 10)
Henkie.Text += "0" + sec;
else
Henkie.Text += sec.ToString();
}
}
else
{
sw.Stop();
Response.Redirect("Ingelogd2.aspx");
}
}
}
}
The result I'm getting from this code is for example: 00:14 ( after 14 seconds displayed on the label "Henkie")
Now I've tried to add hours aswell, so I've made this code:
public partial class Ingelogd2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sw = new Stopwatch();
sw.Start();
}
}
private static Stopwatch sw;
protected void tm1_Tick(object sender, EventArgs e)
{
long sec = sw.Elapsed.Seconds;
long min = sw.Elapsed.Minutes;
long hour = sw.Elapsed.Hours;
long day = sw.Elapsed.Days;
if (day < 1)
{
if (hour < 10)
Henkie.Text = "0" + hour;
else
Henkie.Text = hour.ToString();
Henkie.Text += " : ";
if (min < 10)
Henkie.Text = "0" + min;
else
Henkie.Text = min.ToString();
Henkie.Text += " : ";
if (sec < 10)
Henkie.Text += "0" + sec;
else
Henkie.Text += sec.ToString();
}
else
{
sw.Stop();
Response.Redirect("Ingelogd2.aspx");
}
}
}
}
I wanted so it would display for example (00:12:16 after 0 hours, 12 minutes, 16 seconds) but I't doesnt work. It only displays 12:16 after 0 hours, 12 minutes, 16 seconds. I have no idea why this doesn't work. Can somebody help me out?
Upvotes: 0
Views: 207
Reputation: 7448
I have one question for you, which I'd love you to answer before you go on and read the actual solution.
Why are you doing all that? All that code I mean. All that manipulations, adding zeroes, all those if-else statements.
The real question is why complicate something simple?
Now your answer. Just display the Elapsed
property. This will internally call the ToString
with the c
format, which will display hh:mm:ss
with optional days if present.
And if you want to omit, let's say, the hours in the first example you still don't need to write all that code, you just:
sw.Elapsed.ToString("mm\\:ss")
Upvotes: 3