Home > front end >  Get the Year and remaining days from two dates in WINFORM C#
Get the Year and remaining days from two dates in WINFORM C#

Time:07-12

I am trying to get the year(s) from two dates, and if the year(s) are not integer e.g. 2, 3 then I need to resolve the remaining days.

This is a rough code that I have so far:

DateTime inTime = Convert.ToDateTime(LblFirstDate.Text);
DateTime outTime = Convert.ToDateTime(LblSecondDate.Text);

double VTotalDay = outTime.Subtract(inTime).Days;

if (VTotalDay < 365)
{
    LblDays.Text = "Days: "   VTotalDay.ToString();
}
else
{
    double VOver365 = (outTime - inTime).Days / 365.25;
    LblDays.Text = "Years: "    VOver365.ToString();
}

Entering these dates: 7/11/2022, 6/29/2024 will yield 1.9685 which is a over a year but under 2 years.

Most of the example I found only show Year, Month and days remaining.

I trying to get the remaining days from this. I do not need the month, just the days. E.g. 1 year xxx days.

Any suggestion is appreciated. Thx

CodePudding user response:

What you need to do is take the floor of VOver365 for the years and use the modulus operator to get the number of days.

var years = Math.Floor(VOver365);
var days = (outTime - inTime).Days % 365.25;

CodePudding user response:

I used enter image description here

  • Related