Home
C#
DateTime Subtract Method
This page was last reviewed on May 30, 2022.
Dot Net Perls
DateTime Subtract. In a C# program, one DateTime can be subtracted from another. This returns the difference in time between the 2 dates.
DateTime
For example, the difference between December 25 and January 1 in the year 2008 is seven days. The Subtract() method can be used for this purpose.
Example. We use the Subtract method with one argument on the DateTime struct instance. We must subtract the smaller date from the larger date.
struct
Next We see that the difference between Christmas (December 25) and New Year's Day (January 1) is seven days at the end of 2008.
Info Note how the DateTime constructors are passed three arguments. These specify the year, the month, and the day.
Detail If you subtract a later date from an earlier date, you can receive a negative TimeSpan value.
Note For example, change the "newYears" parameters to be the year 2007, and you will get -724 days (negative time).
using System; class Program { static void Main() { // Create DateTime instances for December 25 and January 1. // ... Then compute the difference with Subtract. // ... Write the result. DateTime christmas = new DateTime(2008, 12, 25); DateTime newYears = new DateTime(2009, 1, 1); TimeSpan span = newYears.Subtract(christmas); Console.WriteLine(span); Console.WriteLine("{0} days", span.TotalDays); } }
7.00:00:00 7 days
Discussion. Each DateTime struct stores a ticks field—this is a long type representation of the time. When using Subtract, the long fields from the two DateTime instances are simply subtracted.
long, ulong
And This can be implemented using low-level intermediate language. Please look inside Subtract with IL Disassembler.
Intermediate Language
Summary. Subtract() receives one argument and returns a TimeSpan instance indicating the elapsed time. Typically we subtract a smaller and earlier date from the larger date.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 30, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.