Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
977 views
in Technique[技术] by (71.8m points)

c# - Get a textbox to display days difference between 2 date pickers

I have 2 datetime pickers and i want to display number of days between them on a text box if a user selects a date.

The problem with my code is that it is not giving me correct answers and the TimeSpan doesn't seem to work.

When i choose different dates it gives me answer 10.999998008713 days instead of 11 days and I don't know if i need to do math roundup

    private void btnCalc_Click(object sender, EventArgs e)
    {        
          DateTime start = ArrivalDate.Value;
          DateTime finish = DepartureDate.Value;

          TimeSpan numberOfNights = finish-start;
          double TotalDays= numberOfNights.Days;
          txtBoxNum.Text = (numberOfNights.ToString());
   }

   private void ArrivalDate_ValueChanged(object sender, EventArgs e)
   {
       DepartureDate.Value = ArrivalDate.Value.AddDays(1);
   }

   private void DepartureDate_ValueChanged(object sender, EventArgs e)
   {
       if (DepartureDate.Value < ArrivalDate.Value)
       {
           MessageBox.Show("Cannot be less than previous date");
           DepartureDate.Value = ArrivalDate.Value.AddDays(1);
           snip...
       }
   }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

i dont know if i need to do math roundup

Neither do we. 10.999998008713 days is about 10 days, 23 hours, 59 minutes and 59 seconds. Do you want to count that as 11 days? If so what about 10 days, 23 hours, 59 minutes and 58 seconds? At some point you are going to have to decide what the cutoff between 10 days and 11 days is. This probably depends on your business rules and we don't know that.

Also, numberOfNights.Days is the day component of your numberOfNights value; so for November 4 2013 that would be 4. Are you sure that's what you want? You don't want numberOfNights.TotalDays, which would be the elapsed time between your finish and start in days?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...