如何将两个日期与上一个/旧两个日期进行比较

时间:2018-10-22 10:43:26

标签: c# sql asp.net

我必须将“开始日期”和“结束日期”与数据库中“日期”持续时间的上一个条目进行比较,实际上我想执行预付款,我计算了“开始日期”和“结束日期”之间的“月数”,并为预先付款,现在我要确保如果我创建的工资和月数位于所创建的预先付款的工资之内,然后显示一条验证错误消息,指出在此期间内已支付的预先付款。

谢谢。

2 个答案:

答案 0 :(得分:0)

我认为以下内容应该有效。当我还在学习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}");

            }
        }
    }
}

答案 1 :(得分:-2)

将过去和当前日期转换为字符串,然后进行比较 因为日期/时间/年/月,即日期始终为.date格式,所以您必须在字符串中进行更改,然后进行比较