首页 > 解决方案 > 如何将两个日期与上一个/旧两个日期进行比较

问题描述

我必须将开始日期和结束日期与数据库中日期持续时间的先前条目进行比较,实际上我想执行预付薪水,我计算了开始日期和结束日期之间的月份数,并提前创建了计算月份的薪水,现在我想确保如果我创建的薪水和月份位于创建的预支薪金内,则显示一条验证错误消息,即在此期间支付的预支薪金。

提前致谢。

标签: c#sqlasp.net

解决方案


我认为下面应该工作。由于我仍在学习 C#,因此不能 100% 确定它是最有效的还是遵循写作惯例的。如果是这样,请指出我可以改进的地方。但基本上,逻辑获取旧的开始日期和结束日期计算出天数的差异并将其添加到开始日期并进行比较以查看 startDate 是否大于新日期。如果抛出验证消息,则添加差异。由于您没有提供任何代码,因此您必须以自己的方式实现这一点。(你需要为我刚刚忘记的结束做同样的事情)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackQuesionsPractice
{
    class Program
    {
        static void Main(string[] args)
        {

            //These will be the current dates in your database which you said you use to calculate the months * salary
            DateTime CurrentStart = new DateTime(2013, 1, 1);
            DateTime CurrentEnd = new DateTime(2014, 2, 1);

            //Work out the how the difference in months between the start and end date
            var diffMonths = (CurrentEnd.Month + CurrentEnd.Year * 12) - (CurrentStart.Month + CurrentStart.Year * 12);

            //Monthly salary * by the difference in months to work out the expected wage due
            int MonthlySalary = 40 * diffMonths;

            //User inserts the new dates into the database
            DateTime NewStart = new DateTime(2013, 5, 1);
            DateTime NewEnd = new DateTime(2015, 2, 1);

            //Workout out the total days between the old start and end date
            var diffDays = (CurrentEnd - CurrentStart).TotalDays;

            //Add the total days onto the old date and check to see it it's greater than the current date
            if (CurrentStart.AddDays(diffDays) > NewStart)
            {
                Console.WriteLine("The newly entered start date falls within the last date range saved in the database");
            }
            else {

                //Salary due to the employee 
                Console.WriteLine($"The amount of salary due is: {MonthlySalary}");

            }
        }
    }
}

推荐阅读