Wednesday, April 24, 2019

Function to calculate the difference between two dates using C#



In this article, we are going to look at how to calculate the date difference between two dates in C#. Like in other OOP languages, C# has two data types to store the results. 
  • DateTime Structure
  • TimeSpan Structure


DateTime Struct

DateTime Structure is a child of System namespace and no any other external libraries needed for this. Normally DateTime constructor takes minimum 3 parameters; year, month and date. Further, the constructor can be overloaded with multiple parameters to get the time range. To take the date and time ranges, we can use Calendar data type as well. But it is recommended to use DateTime struct, as it is the most efficient and accurate way.
            /* Year=2019 Month=03 Date=01*/
            DateTime datetime = new DateTime(2019, 03, 01);

            /* Year=2019 Month=03 Date=01 Hour=00 Minute=00 Second=00*/
            DateTime datetime = new DateTime(2019, 03, 01, 00, 00, 00);

TimeSpan Struct
TimeSpan is considered as the data type which is used to store the length of time. Just like the DateTime struct, it is also implemented as a struct and has several overloaded constructors. TimeSpan Structure too is a child of System namespace and in our example, we are going to use it to store the difference between the dates. Hence, TimeSpan can be used for many date manipulations as shown below.
           TimeSpan days = TimeSpan.FromDays(1);               
            TimeSpan hours = TimeSpan.FromHours(1);
            TimeSpan mins = TimeSpan.FromMinutes(1);

            Console.WriteLine(days); 
            Console.WriteLine(hours);
            Console.WriteLine(mins);

What is a Struct?

Unlike classes, structs can be used without instantiating with a new keyword. Structs provide better performance when the value-type collection to be grouped is small. Structs cannot inherit either from the same struct type or even a different class. To define a struct, we need to use the word struct before the name of the class.
          public struct Employee {
            public int age;

            public setAge(int newAge)
            {
                age = newAge;
            }
        }
In this example, we are calculating the difference between the dates using 2 methods.
·         Date Difference by Subtract() Method
·         Date Difference by Subtraction(-) Operator

Date Difference by Subtract() Method
DateTime structure has its own predefined method Subtract() which takes a date as the argument and returns the difference between the specified dates. It results in TimeSpan value and we can use different properties defined by the TimeSpan to display the output as per our requirement.
class DateDifference
{
  public void getDateDiff(DateTime date1, DateTime date2) {
     DateTime oldDate = new System.DateTime(date1.Year, date1.Month,
                          date1.Day, date1.Hour, date1.Minute, date1.Second);
     DateTime newDate = new System.DateTime(date2.Year, date2.Month,
                          date2.Day, date2.Hour, date2.Minute, date2.Second);
     TimeSpan dateDiff = newDate.Subtract(oldDate); //using substraction method
     Console.WriteLine($"Date Difference is = {dateDiff.Days}");
  }
  
  static void main(string[] args)
  {
     DateTime date1 = new System.DateTime(2019, 3, 1, 12, 0, 0);
     DateTime date2 = new System.DateTime(2019, 3, 2, 13, 0, 0);
     DateDifference dateDifference = new DateDifference();
     dateDifference.getDateDiff(date1, date2); //output-> 1

   }
 }
In here we are using only the Days property of the TimeSpan structure. Nevertheless, there are many other properties like Hours, Minutes, Seconds, TotalDays etc.


Date Difference by Subtraction (-) Operator

The easier way of finding the date difference is by using the minus operator. In the below example, we’ll be creating a method called getDateDiff() and passes two DateTime arguments to it. From the passed arguments; Year, Minutes, Seconds etc. are extracted and passed to the constructor. Finally, getDateDiff() method is invoked in the main method using the values of the user. This method too results in the same output as the Subtract() method.
class DateDifference
{
  public void getDateDiff(DateTime date1, DateTime date2) {
     DateTime oldDate = new System.DateTime(date1.Year, date1.Month,
                          date1.Day, date1.Hour, date1.Minute, date1.Second);
     DateTime newDate = new System.DateTime(date2.Year, date2.Month,
                          date2.Day, date2.Hour, date2.Minute, date2.Second);
     TimeSpan dateDiff = newDate - oldDate; //using substraction operator
     Console.WriteLine($"Date Difference is = {dateDiff.Days}");
  }
  
  static void main(string[] args)
  {
     DateTime date1 = new System.DateTime(2019, 3, 1, 12, 0, 0);
     DateTime date2 = new System.DateTime(2019, 3, 2, 13, 0, 0);
     DateDifference dateDifference = new DateDifference();
     dateDifference.getDateDiff(date1, date2); //output-> 1

   }
 }


Apart from the previously stated 2 methods, VB.NET namespace provides DateDiff() function to calculate date difference between two dates. For that, we need to add the VB script to the C# project and it is not recommended to practice in C# environment. So far we have calculated the date difference using two methods, but one of the important points to be noticed is that, both the dates we used are considered to be in the same time zone. What happens if the dates are in different time zones? For that, we can format our final output as follows.

TimeSpan withTimezones = newDate.ToUniversalTime().Subtract(oldDate.ToUniversalTime());

By using ToUniversalTime() method, we are converting the two values into a common time zone before subtraction, so that no any other confusion occur during the conversion.

No comments:

Post a Comment