Thursday, August 25, 2016

Counting Period Between Two Dates

Categories:

Here is sample code C# to count period between two dates:

Console.WriteLine("Enter start date: YYYY/MM/DD");
string s_startDate = Console.ReadLine();
Console.WriteLine("Enter end date: YYYY/MM/DD");
string s_endDate = Console.ReadLine();
DateTime startDate = Convert.ToDateTime(s_startDate);
DateTime endDate = Convert.ToDateTime(s_endDate);

//Add 1 day because of including the first day
endDate = endDate.AddDays(1);

double countMonth = (endDate.Month + endDate.Year * 12) - (startDate.Month + startDate.Year * 12);

//The divisor, I used 30 (option), you can use total days of the month if needed;
double months = countMonth + ((double)(endDate.Day - startDate.Day) / 30);
            
//Rounding into 2 decimals
decimal result = Math.Round((decimal)months, 2);
Console.WriteLine();
Console.WriteLine("Total of Period: " + result.ToString());
Console.ReadKey();

Spread The Love, Share Our Article

Related Posts

No Response to "Counting Period Between Two Dates"

Post a Comment