-1

I've been asked to make a change to a form but a bit unsure how to tackle it:

The number of hire days calculation needs changing.

If the start date and end date are the same the calculation should be one day- it is done on a 24 hour basis – calculate the number of hours, divide by 24 and round up to the nearest whole number

So from 14/11/2013 08.00 to 14.11.2013 20.30 is 12.5 hours - 12.5 divided by 24 = 0.52 round up = 1 day

14.11.2013. 08.00 to 15.11.2013 20.30 is 36.5 hours – 36.5/24= 1.52 – round up = 2 days

can anyone help??

this is my code at the moment:

private void noOfDaysRequired()
{
    decimal days = 0;

    if (txtEndTimeHH.Text != "" || txtEndTimeMM.Text != "")
    {
        DateTime bookingStartTime = DateTime.Parse(txtStartDate.Text + " " + txtStartTimeHH.Text + ":" + txtStartTimeMM.Text);
        DateTime bookingEndTime = DateTime.Parse(txtEndDate.Text + " " + txtEndTimeHH.Text + ":" + txtEndTimeMM.Text);
        bookingStartTime = bookingStartTime.AddMinutes(15);
        TimeSpan noOfDays = bookingEndTime - bookingStartTime;
        days = noOfDays.Days;
        if (days == 0)
        {
            days += 1;
        }
        if (bookingEndTime.TimeOfDay.Ticks > bookingStartTime.TimeOfDay.Ticks)
        {
            days = days + 1;
        }

        lblDaysRequired.Text = days.ToString();
    }
}
Trayek
  • 4,390
  • 3
  • 22
  • 38
Neil
  • 1
  • 3
  • 4
    Show some code, and explain where you're having trouble. You're more likely to get help when you show you've made an effort. – Rotem Nov 18 '13 at 10:06
  • Use Math.Ceiling function around your calculation. Get the timespan between the days like shown here: http://stackoverflow.com/questions/4946316/showing-difference-between-two-datetime-values-in-hours – Terry Nov 18 '13 at 10:07
  • How many days is "from _14.Nov.2013 15:30_ to _15.Nov.2013 09:30_" supposed to give? One or two? – Jeppe Stig Nielsen Nov 18 '13 at 11:10

2 Answers2

0

Have a look at the TimeSpan structure. It has an Hours property that you can use and the TotalDays property as well.

TimeSpan time = new TimeSpan(0, 36, 5, 0, 0);
var days = time.TotalDays;
David Pilkington
  • 13,043
  • 3
  • 36
  • 65
0

Try this code

        DateTime a = new DateTime(2013,11, 18, 02, 00, 00);
        DateTime b = new DateTime(2013, 11, 20, 03, 30, 00);
        double days = 0;
        TimeSpan duration = b - a;

        if (duration.TotalDays > 0 && duration.TotalDays < 1)
        {
            days = 1;
        }
        else if (duration.TotalHours > 0)
        {
            days = Math.Ceiling(duration.TotalHours / 24);
        }
raza rabbani
  • 439
  • 3
  • 11
  • Not elegant. Why do you do `Convert.ToDouble` on something which is already a `double`; that's a no-op, for sure? Why do you use hours and divide by 24 when you can use "days" immediately? – Jeppe Stig Nielsen Nov 18 '13 at 11:21