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 hour开发者_运维百科s = 1:00pm
- 5:00pm - 2 hours = 3:00pm
- 5:30pm - :45 = 4:45
and so on.
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));
Or you can also use the DateTime.Subtract(TimeSpan)
method analogously.
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.
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;
To subtract a year:
DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);
Hi if you are going to subtract only Integer value from DateTime then you have to write code like this
DateTime.Now.AddHours(-2)
Here I am subtracting 2 hours from the current date and time
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)
try this
namespace dateandtime
{
class DatesTime
{
public static DateTime Substract(DateTime now, int hours,int minutes,int seconds)
{
TimeSpan T1 = new TimeSpan(hours, minutes, seconds);
return now.Subtract(T1);
}
static void Main(string[] args)
{
Console.WriteLine(Substract(DateTime.Now, 36, 0, 0).ToString());
}
}
}
TimeLeftToOpen= new TimeSpan(TimeLeftToOpen.Hours, TimeLeftToOpen.Minutes, TimeLeftToOpen.Seconds - 1);
精彩评论