How to get time difference of two values taken by Winforms DateTimePicker only considering hours minutes and seconds and without miliseconds in C#?

I'm getting values from two dateTimePickers and I need to get the time difference between them. Now, I'm calculating the difference using the below code, but I'm getting a wrong time difference with Milliseconds. Is there a way to calculate the time difference without considering Milliseconds. WindowsFormScreenshot

TimeSpan difference = dateTimePicker2.Value - dateTimePicker1.Value;

Example 1;

  • Start time : 4/24/2022 2:30:11 PM
  • end time : 4/24/2022 2:30:11 PM
  • Actual difference : -00:00:00.0049863
  • Expected difference : 00:00:00

Example 2;

  • Start time : 4/24/2022 2:29:01 PM

  • end time : 4/24/2022 10:29:01 PM

  • Actual difference : 07:59:59.9037925

  • Expected difference : 08:00:00

Example 3;

  • Start time : 4/24/2022 4:24:28 PM

  • end time : 4/24/2022 10:30:28 PM

  • Actual difference : 06:05:59.9648821

  • Expected difference : 06:06:00

It will give expected answers, when I'm retyping the time value in both dateTimePickers in Winform but doesn't work when I didn't retype minutes field in each dateTimePicker.

I don't want to round up the answers. I want to do the difference calculation without considering milliseconds. So that it will give correct answers for what ever the values we parse for dateTimePickers.

(I'm a newbie to c#. so I'm sorry if I'm not much clear. Thank you so much!)

3 answers

  • answered 2022-04-24 09:29 Elec1

    You may read hours, minutes, and seconds separately:

    int hourCnt = difference.Hours;
    int minuteCnt = diffenrence.Minutes;
    int secondCnt = difference.Seconds;
    

  • answered 2022-04-24 09:30 Morten Bork

       DateTime adjustedDateTimePicker2 = dateTimePicker2.Value.AddMilliseconds(dateTimePicker2.Value.Millisecond * -1);
            
       DateTime adjustedDateTimePicker1 = DateTimePicker.Value.AddMilliseconds(dateTimePicker.Value.Millisecond * -1);
            
       TimeSpan difference = adjustedDateTimePicker2 - adjustedDateTimePicker1;
    

  • answered 2022-04-24 11:16 Reza Aghaei

    You can first round the timespan, then format the result using a Custom Timespan format string like "hh':'mm':'ss" or @"hh\:mm\:ss":

    var d1 = DateTime.Parse("4/24/2022 4:24:28 PM");
    var d2 = DateTime.Parse("4/24/2022 10:30:28 PM");
    var d = d2 - d1;
    
    int precision = 0;
    const int TIMESPAN_SIZE = 7;
    int factor = (int)Math.Pow(10, (TIMESPAN_SIZE - precision));
    TimeSpan roundedTimeSpan = 
        new TimeSpan(((long)Math.Round((1.0 * d.Ticks / factor)) * factor));
    
    MessageBox.Show(roundedTimeSpan.ToString(@"hh':'mm':'ss"));
    

    Which shows:

    06:06:00
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum