w3resource

C#: Difference between two dates in days

C# Sharp DateTime: Exercise-30 with Solution

Write a C# Sharp program to get the difference between two dates in days.

Sample Solution:-

C# Sharp Code:

using System;

class Example30
{
    public static void Main() 
    {
        // Establish DateTime objects representing start and end dates
        DateTime start = new DateTime(2010, 6, 14);
        DateTime end = new DateTime(2016, 08, 14);

        // Calculate the difference between 'end' and 'start' DateTime objects
        TimeSpan difference = end - start; // Create TimeSpan object representing the duration

        // Extract the difference in days and write it to the console
        Console.WriteLine("Difference in days: " + difference.Days);
    }
}

Sample Output:

Difference in days: 2253  

Flowchart:

Flowchart: C# Sharp Exercises - Difference between two dates in days

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to convert the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style.
Next: Write a C# Sharp program to convert the value of the current DateTime object to local time.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/datetime/csharp-datetime-exercise-30.php