Share via

Why does days difference between two datetimepicker give two different results?

MUHAMMET GUNES 20 Reputation points
2023-07-03T19:48:37.3+00:00

I have a really interesting issue. You can find the codes below;

The problem occurs when I run this Windows form application, the Duration textbox gives the result accurately; For instance; (30, Sep, 2023 - 01, Sep, 2023) + 1 = 30 Days. However, Sometimes and Howcome It doesn't accurately by giving the result and shows as 29 Days. Why do you think sometimes it doesn't read + 1 in the code?

// This function arranges duration
        private void ArrangeDuration()
        {
            DateTime endDate, startDate;
            TimeSpan duration;
            int dur;
            endDate = enddateTimePicker.Value;
            startDate = startdateTimePicker.Value;
            duration = endDate - startDate;
            dur = duration.Days + 1;
            durationtextBox.Text = dur.ToString() + " Days";
        }

// Arranges Duration Textbox when datetimepicker value changes
		private void startdateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            ArrangeDuration();
            enddateTimePicker.Value = startdateTimePicker.Value;
        }

        private void enddateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            ArrangeDuration();
        }
Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other

A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Anonymous
2023-07-04T03:19:45.62+00:00

Hi @MUHAMMET GUNES , Welcome to Microsoft Q&A.

Maybe it's an effect of the timing part.

If the time portion of the is set to a time earlier than the time portion of the , this may result in a duration of 29 days instead of 30 days.

Try using:

duration = endDate.Date - startDate.Date;

Best Regards,

Jiale


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.