C# 我想将小时或分钟添加到当前时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/902565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I want add hours or minutes to current time
提问by
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?
例如,我有问题的时间和完成它们的预期时间
如何添加?
(DateTime.Now.ToShortDateString() +.......)
回答by Jhonny D. Cano -Leftware-
You can use other variable
您可以使用其他变量
DateTime otherDate = DateTime.Now.AddMinutes(25);
DateTime tomorrow = DateTime.Now.AddHours(25);
回答by Mark Simpson
You can also add a TimeSpan to a DateTime, as in:
您还可以将 TimeSpan 添加到 DateTime,如下所示:
date + TimeSpan.FromHours(8);
回答by Peter Stuer
You can use the operators +
, -
, +=
, and -=
on a DateTime with a TimeSpan argument.
您可以在带有 TimeSpan 参数的 DateTime 上使用运算符+
、-
、+=
和-=
。
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
有关更多 DateTime 操作的详细概述,请参阅THIS
回答by Alp Altunel
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
}