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

时间:2014-10-03 00:08:17

标签: c# c#-4.0 c#-3.0 c#-2.0

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

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。我可以硬编码并验证日期和月份,并检查输入年份之间的差异,以实现这一目标,但有更好的方法可以做到吗?

1 个答案:

答案 0 :(得分:0)

我希望这会有所帮助

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.
}

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