检查财政年度日期的逻辑更好

本文关键字:更好 日期 检查 | 更新日期: 2023-09-27 18:25:27

我已经有了一个逻辑来检查输入的日期是否正是财政年度日期

if (DateTime.IsLeapYear(endate.Year))
{
    if (totalDay != 366)
    {
        error("Please make sure start and end dates are financial year dates.<br />E.g.<br /> Start Date:01/07/2012 <br /> End Date :30/06/2013");
        return;
    }
}
else
{
    if (totalDay != 365)
    {
        error("Please make sure start and end Dates are Financial year dates.<br />E.g.<br /> Start Date:01/07/2012 <br /> End Date :30/06/2013");
        return;
    }
}

通过这种方式,我正在检查输入的日期是否正好有1年的差异。但它不会检查用户是否输入了确切的开始日期01/07/20XX-结束日期30/06/20XX。我可以硬编码和验证日期和月份,并检查输入年份之间的差异来实现这一点,但有更好的方法吗?

检查财政年度日期的逻辑更好

我希望这将帮助

DateTime starDate = TextToDate(txtStartDate.Text); //01/07/2013
// or startDate = DateTimePicker1.Value;
DateTime endDate = TextToDate(txtEndDate.Text);  //30/06/2014
// or endDate = DatetTimePicker2.Value
DateTime calculatedEndDate = startDate.AddYears(1).AddDays(-1);
// 01/07/2013 .AddYears(1) ==> 01/07/2014 .AddDays(-1) ==> 30/06/2014
// Note for above line:
//     if you will be using the start date and end date in an sql query
//     remove the call to function AddDays(-1)
//     for display purposes, keep the function AddDays(-1)

if(endDate != calculatedEndDate)
// note: if DateTimePicker is returning time component, then you will need to compare each (year, month and day)
{
    // show error message
}
else
{
    // dates are 1 year apart.
}

或者,您可以要求用户只输入开始日期,然后计算结束日期。