简体   繁体   English

从 WINFORM C# 中的两个日期获取年份和剩余天数

[英]Get the Year and remaining days from two dates in WINFORM C#

I am trying to get the year(s) from two dates, and if the year(s) are not integer eg 2, 3 then I need to resolve the remaining days.我试图从两个日期获取年份,如果年份不是整数,例如 2、3,那么我需要解决剩余的天数。

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.输入这些日期: 2022 年 7 月 11 日、2024 年 6 月 29 日将产生1.9685 ,即超过一年但不到 2 年。

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.我不需要月份,只需要几天。 Eg 1 year xxx days.例如 1 年 xxx 天。

Any suggestion is appreciated.任何建议表示赞赏。 Thx谢谢

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.你需要做的是取VOver365的年数,使用模算子得到天数。

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

I used Aca suggestions and resolved the issue.我使用了Aca的建议并解决了这个问题。

Here is the modified code:这是修改后的代码:

            DateTime inTime = Convert.ToDateTime(LblFirstDate.Text);
            DateTime outTime = Convert.ToDateTime(LblSecondDate.Text);
            
            double VTotalDay = outTime.Subtract(inTime).Days;

            if (VTotalDay < 365)
            {
                LblYears.Text = "Days: " + VTotalDay.ToString();
            }
            else
            {
                double VOver365 = (outTime - inTime).Days / 365.25;
                var days = (outTime - inTime).Days % 365.25;

                LblYears.Text = Math.Floor(VOver365).ToString() + " Years" + " " + (Math.Round(days, 0)).ToString() + " Days";
            }

If the total days are less then 365 it display the total days, if the total days are over 365 it will make the calculation to math.floor and display the Year from the variable VOver365 .如果总天数小于365 ,则显示总天数,如果总天数超过365 ,它将计算到math.floor并显示变量VOver365中的年份。 It then Math.Round the remaining days from the variable days .然后它Math.Round从变量days剩余的天数。

For date range 7/11/2022, 6/29/2024 from this 1.9685 to对于日期范围2022 年 7 月 11 日、2024 年 6 月 29 日,1.9685在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM