Back to Exercise List

C# Exercise Program - Days between two dates

Question: Write a program in C# to find number of days between two dates.

This program takes two DateTime values are input. It then computes the number of days between the two dates.
Solution:
using System;
using System.Linq;
using System.Collections.Generic;

namespace CosmicLearn
{
    public static class CosmicExercise
    {
        public static double DaysBetween(DateTime start, DateTime end)
        {
            return (end - start).TotalDays;
        }
        public static void Main(String[] args)
        {
            DateTime startDate = new DateTime(2017, 12, 21);
            DateTime endDate = new DateTime(2017, 12, 27);

            Console.WriteLine("Number of days between = " 
                              + DaysBetween(startDate, endDate));
        }
    }
}