Calculate difference between two dates in C# and VB

In at least one of your projects, you’ll have to calculate the difference between the two dates. And if you enjoyed programming in C# or VB already, you’ll enjoy even more what tools they have provided to do so.

Calculating the difference between dates in C#:

Calculating the difference between dates in VB:

So both languages work the same way with the TimeSpan object. But what you notice is the lack of calculating the difference in, for example, years or months. There is no standard solution for this in C#. But VB (And SQL) however has the ‘DateDiff‘ function which allows to calculate the difference in more ways than the above examples:

This looks quite nice. But I’ll still suggest trying to use the TimeSpan objects as much as possible. Because after testing these two, I’ve noticed a difference between returned values from these functions. This will probably have to do with how the calculation is done for the time-difference when nor hours, minutes or seconds are given:

If you still want to use the ‘DateDiff’ function in C#, you can always reference the Microsoft.VisualBasic dll in your project and use the function from it. Or you can use the ‘DateDiff’ functions used by Linq when generating SQL-queries. These generate the same results as the VB ‘DateDiff’ functions, but offers other formats:

Leave a Reply

Your email address will not be published. Required fields are marked *