Warm tip: This article is reproduced from serverfault.com, please click

C# DateTime + TimeSpan = an extra 12 hours?

发布于 2020-11-28 21:01:45

I want to log time spent on a job, and I would like to accumulate that time over many entries for work on the same job at different times of the day.

I have it recording time, and adding the time difference together and it works....except my output looks like this:

Original Time: 00:00:30
Addition Time: 00:00:10
TotalTime Out: 12:00:40

In this line of code:

totTime.Text = dt4.ToString("hh:mm:ss");

If I don't add the "hh:mm:ss" it adds up correctly, but includes the date which I don't really want. If that helps to narrow it down.

Anyone know why it is adding 12 hours here? I can't see a reason for it to do so at all.

My code to get the time entries and calculate the differences looks like this:

public void startbutton_Click(object sender, EventArgs e)
        {

            startTime.Text = DateTime.Now.ToString("hh:mm:ss");

        }

public void stopbutton_Click(object sender, EventArgs e)
        {

            stopTime.Text = DateTime.Now.ToString("hh:mm:ss");

            DateTime dt1 = DateTime.ParseExact(startTime.Text, "hh:mm:ss", new DateTimeFormatInfo());
            DateTime dt2 = DateTime.ParseExact(stopTime.Text, "hh:mm:ss", new DateTimeFormatInfo());

            TimeSpan ts1 = dt2.Subtract(dt1);

            diffTime.Text = ts1.ToString();

            if (String.IsNullOrEmpty(totTime.Text))
            {
                totTime.Text = ts1.ToString();
            }
            else if (totTime.Text != "")
            {
                DateTime dt3 = DateTime.ParseExact(diffTime.Text, "hh:mm:ss", new DateTimeFormatInfo());

                DateTime dt4 = dt3 + ts1;
                totTime.Text = dt4.ToString("hh:mm:ss");
            }

Thanks.

Questioner
user13965861
Viewed
11
RaceRalph 2020-11-29 06:28:43

No 12 hours get added to your measured time. You simply display TimeSpan as time of day.

Here you convert TimeSpan to a string and write it to diffTime.Text:

        TimeSpan ts1 = dt2.Subtract(dt1);
        diffTime.Text = ts1.ToString();

Here you parse diffTime.Text as DateTime:

            DateTime dt3 = DateTime.ParseExact(diffTime.Text, "hh:mm:ss", new DateTimeFormatInfo());

Parsing TimeSpan as DateTime is fundamentally wrong. If TimeSpan is 40 seconds and you parse it as DateTime, the resulting time of day is 40 seconds past midnight, which is 12:00:40 AM. This is what you see on the screen.

As @Flydog57 suggested - make all calculations using DateTime and TimeSpan. Only the final result should be converted to text and displayed.