I want add hours or minutes to current time

前端 未结 4 1864
小蘑菇
小蘑菇 2020-12-03 13:40

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?

 (Date         


        
相关标签:
4条回答
  • 2020-12-03 13:55

    You can use other variable

    DateTime otherDate = DateTime.Now.AddMinutes(25);
    DateTime tomorrow = DateTime.Now.AddHours(25);
    
    0 讨论(0)
  • 2020-12-03 13:57

    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

    0 讨论(0)
  • 2020-12-03 14:11

    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
    }
    
    0 讨论(0)
  • 2020-12-03 14:14

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

    date + TimeSpan.FromHours(8);
    
    0 讨论(0)
提交回复
热议问题