Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

datetime - C#: what is the easiest way to subtract time?

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

and

5:00pm - 2 hours = 3:00pm

and

5:30pm - :45 = 4:45

and so on.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...