Maldakheel
Maldakheel

Reputation:

Add hours or minutes to the current time

I want to increase time to current time.

For example, I have the time of the problem and the expected time to complete them. How can I add to it?

 (DateTime.Now.ToShortDateString() + ...)

Upvotes: 30

Views: 106056

Answers (4)

Jhonny D. Cano -Leftware-
Jhonny D. Cano -Leftware-

Reputation: 18013

You can use other variables:

DateTime otherDate = DateTime.Now.AddMinutes(25);
DateTime tomorrow = DateTime.Now.AddHours(25);

Upvotes: 64

Alp Altunel
Alp Altunel

Reputation: 3443

Please note that you may add - (minus) sign to find minutes backwards

DateTime begin = new DateTime();
begin = DateTime.ParseExact("21:00:00", "H:m:s", null);

if (DateTime.Now < begin.AddMinutes(-15))
{
    //if time is before 19:45:00 show message etc...
}

and time forward

DateTime end = new DateTime();
end = DateTime.ParseExact("22:00:00", "H:m:s", null);


if (DateTime.Now > end.AddMinutes(15))
{
    //if time is greater than 22:15:00 do whatever you want
}

Upvotes: 2

Peter Stuer
Peter Stuer

Reputation: 1976

You can use the operators +, -, +=, and -= on a DateTime with a TimeSpan argument.

DateTime myDateTime = DateTime.Parse("24 May 2009 02:19:00");

myDateTime = myDateTime + new TimeSpan(1, 1, 1);
myDateTime = myDateTime - new TimeSpan(1, 1, 1);
myDateTime += new TimeSpan(1, 1, 1);
myDateTime -= new TimeSpan(1, 1, 1);

Furthermore, you can use a set of "Add" methods

myDateTime = myDateTime.AddYears(1);                
myDateTime = myDateTime.AddMonths(1);              
myDateTime = myDateTime.AddDays(1);             
myDateTime = myDateTime.AddHours(1);               
myDateTime = myDateTime.AddMinutes(1);            
myDateTime = myDateTime.AddSeconds(1);           
myDateTime = myDateTime.AddMilliseconds(1);       
myDateTime = myDateTime.AddTicks(1);     
myDateTime = myDateTime.Add(new TimeSpan(1, 1, 1)); 

For a nice overview of even more DateTime manipulations see THIS

Upvotes: 19

Mark Simpson
Mark Simpson

Reputation: 23365

You can also add a TimeSpan to a DateTime, as in:

date + TimeSpan.FromHours(8);

Upvotes: 5

Related Questions