Tuesday, June 3, 2014

Getting dates and calculating a time interval in C# - Part II

TimeSpan

You can get the source code on GitHub. (I've updated the code a bit.)

TimeSpan is struct with a method subtract that will calculate the number of days between two dates. This means, though, that we are now dealing with a different type from DateTime. DateTime just gives you dates and, as you know from the previous post, I needed to calculate an interval between dates. So how could I use the  TimeSpan type with the DateTime objects I had created?

My first thought was to convert my TimeSpan object to a DateTime object because I knew how to format DateTime to display only the date. But as someone pointed out on Stack Overflow, it doesn't make sense to do it that way. TimeSpan represents, guess what, a span of time. DateTime represents, yes, you guessed it, a date and a time. The date July 12, 2013 is different from the time span 2 days, 12 hours, 30 minutes and 40 seconds.

So here's how it's done:
TimeSpan daysGoneBy = todayDateOnly.Subtract(boughtDateOnly);
Start with a TimeSpan variable, daysGoneBy. On the other side of the equation is largerDate.methodSubtract(argumentIsSmallerDate).

Now, just display the result:
string output;
output = "The number of days elapsed since the vehicle was bought: " + daysGoneBy.ToString("%d");
As you may recall, "d" is a format specifier. Here, "%d" means only the whole number of days will be displayed. (Remember that % is the symbol for modulo.)

It took some work for me to figure this out on my own, putting all the pieces of the puzzle together, and it was a lot of fun. I hope you find it helpful.

No comments:

Post a Comment