Counting Period Between Two Dates - thoriqaziz.com

thoriqaziz.com

Do your hobby

Counting Period Between Two Dates

Share This
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();

No comments:

Post a Comment

Pages