在 C# 中减去时间的最简单方法是什么?
我正在尝试整合一个工具来帮助我制定工作时间表。解决以下问题的最简单方法是什么?
- 上午 8:00 + 5 小时 = 下午 1:00
- 下午 5:00 - 2 小时 = 下午 3:00
- 下午 5:30 - :45 = 4:45
依此类推。
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
- 5:00pm - 2 hours = 3:00pm
- 5:30pm - :45 = 4:45
and so on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这些都可以通过
DateTime.Add(TimeSpan) 完成
因为它支持正时间跨度和负时间跨度。或者您也可以使用
DateTime.Subtract (TimeSpan)
方法类似。These can all be done with
DateTime.Add(TimeSpan)
since it supports positive and negative timespans.Or you can also use the
DateTime.Subtract(TimeSpan)
method analogously.在此处查看所有 DateTime 方法: http://msdn.microsoft.com /en-us/library/system.datetime.aspx
Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
您好,如果您只想从 DateTime 中减去 Integer 值,那么您必须编写如下代码
这里我从当前日期和时间中减去 2 小时
Hi if you are going to subtract only Integer value from DateTime then you have to write code like this
Here I am subtracting 2 hours from the current date and time
这也有效:
减去一年:
This works too:
To subtract a year:
使用 TimeSpan 对象捕获初始时间元素并使用
AddHours
或AddMinutes
等方法。要减去 3 小时,您需要执行AddHours(-3)
。要减去 45 分钟,您需要执行AddMinutes(-45)
Use the TimeSpan object to capture your initial time element and use the methods such as
AddHours
orAddMinutes
. To substract 3 hours, you will doAddHours(-3)
. To substract 45 mins, you will doAddMinutes(-45)
试试这个
try this
原始日期时间 = 新日期时间(年、月、日、8、0、0);
DateTime 更新 = Original.Add(new TimeSpan(5,0,0));
原始日期时间 = 新日期时间(年、月、日、17、0、0);
DateTime 更新 = Original.Add(new TimeSpan(-2,0,0));
原始日期时间 = 新日期时间(年、月、日、17、30、0);
DateTime 更新 = 原始.Add(new TimeSpan(0,-45,0));
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));
TimeLeftToOpen= new TimeSpan(TimeLeftToOpen.Hours, TimeLeftToOpen.Minutes, TimeLeftToOpen.Seconds - 1);
TimeLeftToOpen= new TimeSpan(TimeLeftToOpen.Hours, TimeLeftToOpen.Minutes, TimeLeftToOpen.Seconds - 1);