c#将日期时间日期与时间跨度参数进行比较

时间:2015-04-02 14:44:38

标签: c# datetime

目前,我已设法使我的计划正常运作,因此它比较了两个日期时间日期,如果之前的记录在之前或之前的时间,它会提醒最终用户患者需要检查。

我希望能够比较今天的日期和上一个日期,如果距离最初的预订日期有一个月,它会执行相同的提醒。

private void PatientCheckUp()
{
    SqlConnection connection = new SqlConnection();
    Security security = new Security();
    DateTime timenow = DateTime.Now.Date;
    DateTime lastbooking = new DateTime();
    string previousBooking = "";

    try
    {
        connection.ConnectionString = connectionPath;
        connection.Open();

        SqlCommand cmd = new SqlCommand("SELECT Booking.Booking_Last_Booking, Booking.Booking_FkPatientId FROM Booking WHERE Booking.Booking_FkPatientId = @Patient_Id", connection);
        cmd.Parameters.AddWithValue("@Patient_Id", cbopatientid.Text);
        cmd.ExecuteNonQuery();

        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            while (dr.Read())
            {
                previousBooking = security.Decrypt(dr["Booking_Last_Booking"].ToString(), security.GetPassword());
            }
        }

        lastbooking = Convert.ToDateTime(previousBooking);

        /*Currently checks if the previous booking date is less than or before today, if so it alerts the user */
        if (lastbooking.Date < timenow.Date)
        {
            MessageBox.Show("Patient requires a checks up");
        }
    }
    catch (SqlException sql)
    {
        MessageBox.Show(sql.Message);
    }
    finally
    {
        connection.Close();
        connection.Dispose();
    }
}

2 个答案:

答案 0 :(得分:1)

using System;

public class Program
{
    public static void Main()
    {
        DateTime dt = new DateTime();
        DateTime dt2 = new DateTime();

        dt = DateTime.Now;
        dt2 = dt.AddDays(20);


        TimeSpan ts = dt2.Subtract(dt);

        Console.WriteLine(dt.ToString());
        Console.WriteLine(dt2.ToString());

        if(ts.Days > 30)
        {
        Console.WriteLine("It has been at least a month since last check up");
        }
        else
        {
            Console.WriteLine("It has been "+ ts.Days+" days since last check up");
        }

    }
}

以上是我放在一起的一段示例代码,用于说明如何执行此操作。您可以确定“月”应该是多少天,然后在超过指定阈值时对其执行操作。

Here是我正在玩的DotNetFiddle

答案 1 :(得分:0)

您可以执行以下操作。

if (timenow.Date - lastbooking.Date).Days > 30)
{
    MessageBox.Show("It's been over 30 days since last checkup.");
}
相关问题