views:

74

answers:

4

Hey guys, ive seen a couple posts on this but nothing so far that is specific to this simple operation. I'm trying to put together a tool that will help me make work schedules. What is the easiest way to solve the following:

8:00am + 5 hours = 1:00pm

and

5:00pm - 2 hours = 3:00pm

and

5:30pm - :45 = 4:45

and so on.

+4  A: 

These can all be done with DateTime.Add(TimeSpan) since it supports positive and negative timespans.

DateTime original = new DateTime(year, month, day, 8, 0, 0);
DateTime updated = original.Add(new TimeSpan(5,0,0));

DateTime original = new DateTime(year, month, day, 17, 0, 0);
DateTime updated = original.Add(new TimeSpan(-2,0,0));

DateTime original = new DateTime(year, month, day, 17, 30, 0);
DateTime updated = original.Add(new TimeSpan(0,45,0));
Steve Townsend
ok so where did i go wrong. i added a datetimepicker and assigned its value to a datetime variable. now the math methods aren't showing up
Sinaesthetic
@Sinaesthetic - probably worth posting some code, this is a slightly different question than date-time arithmetic
Steve Townsend
+1  A: 

Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx

Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.

AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.

AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.

AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.

AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.

AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.

AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.

AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.

DJ Quimby
+2  A: 

Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)

Fadrian Sudaman
A: 

This works too:

        System.DateTime dTime = DateTime.Now();

        // tSpan is 0 days, 1 hours, 30 minutes and 0 second.
        System.TimeSpan tSpan 
            = new System.TimeSpan(0, 1, 3, 0); 

        System.DateTime result = dTime + tSpan;
rboarman