How to calculate years from two different date in ASP.NET C#

Gani_tpt 1,586 Reputation points
2024-04-28T17:11:24.31+00:00

I have Employee Admission Date which is stored in SQL table.

In the ASP.NET click event, i want to calculate and find the years from the Admission Date and Current Date.

For example,

Admission Date : 10-MAR-2023

Current Date : 28-APR-2024

condition is below.

If employee admission date is exactly more than 5(five years) from current date's

{

then the system should allow to enter for next admission

}

else (less than or equal to 5 years)

{

system should block the user to enter the admission date

}

How to generate simple logic for the above scenario...?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,292 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,320 questions
{count} votes

Accepted answer
  1. Pinaki Ghatak 2,400 Reputation points Microsoft Employee
    2024-04-29T08:11:15.0266667+00:00

    Hello @Gani_tpt

    Since you did not clarify, if you are trying to implement this logic on the front-end, the backend, or on the SQL itself, you have 3 possibilities to consider.

    C# backend:

    DateTime currentDate = DateTime.Now;
    int differenceInYears = GetDifferenceInYears(admissionDate, currentDate);
    if (differenceInYears > 5)
    {
        // Allow next admission
        // Your logic here...
    }
    else
    {
        // Block user from entering admission date
        // Your logic here...
    }
    

    In SQL proc you may implement this.:

    CREATE PROCEDURE CalculateDifferenceInYears
        @AdmissionDate DATE,
        @CurrentDate DATE
    AS
    BEGIN
        DECLARE @DifferenceInYears INT
        -- Calculate the difference in years
        SET @DifferenceInYears = YEAR(@CurrentDate) - YEAR(@AdmissionDate)
        -- Adjust for leap years
        IF MONTH(@AdmissionDate) = MONTH(@CurrentDate) AND DAY(@CurrentDate) < DAY(@AdmissionDate)
        BEGIN
            SET @DifferenceInYears = @DifferenceInYears - 1
        END
        -- Return the result
        SELECT @DifferenceInYears AS YearsDifference
    END
    

    and then implement it with your front-end like this.

    using (SqlConnection connection = new SqlConnection("YourConnectionString"))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("CalculateDifferenceInYears", connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@AdmissionDate", yourAdmissionDate);
            command.Parameters.AddWithValue("@CurrentDate", DateTime.Now);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                if (reader.Read())
                {
                    int differenceInYears = Convert.ToInt32(reader["YearsDifference"]);
                    // Your logic based on the differenceInYears here...
                }
            }
        }
    }
    
    

    I hope this answers your question.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. hossein jalilian 3,565 Reputation points
    2024-04-28T20:05:49.37+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    Here is a sample implementation using C# within your ASP.NET click event handler:

    protected void YourButtonClickEvent(object sender, EventArgs e)
    {    
        DateTime admissionDate = DateTime.Parse("2023-03-10");
        DateTime currentDate = DateTime.Today;
        int yearsDifference = currentDate.Year - admissionDate.Year;
        if (currentDate.Month < admissionDate.Month || 
    	      (currentDate.Month == admissionDate.Month && currentDate.Day < admissionDate.Day)
    	   )
        {
            yearsDifference--;
        }
        if (yearsDifference > 5)
        {
        }
        else
        {
        }
    }
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful

    0 comments No comments

  2. AgaveJoe 26,151 Reputation points
    2024-04-29T12:53:49.7266667+00:00

    Check if the current date is greater than the admission date + five years.

    This code is straight forward in any language.

    SQL

    DROP TABLE IF EXISTS #DateEx;
    GO
    CREATE TABLE #DateEx (
    	ID			INT IDENTITY,
    	MyDate		DATETIME
    )
    DECLARE @DateNow DATETIME = GETDATE()
    INSERT INTO #DateEx(MyDate)
    VALUES	(DATEADD(YEAR, -1, @DateNow)), 
    		(DATEADD(YEAR, -2, @DateNow)),
    		(DATEADD(YEAR, -5, @DateNow)),
    		(DATEADD(YEAR, -6, @DateNow))
    
    SELECT  MyDate, 
    		GETDATE() [Now],
    		CASE WHEN DateAdd(YEAR, 5, MyDate) <= GETDATE() 
    			THEN 'Greater than or equal to 5 years' 
    			ELSE 'Less than 5 years'
    		END AS [Result]
    FROM #DateEx
    
    
    

    C#

    DateTime myDate = new DateTime(2023, 3, 10);
    DateTime myDatePlus5Years = myDate.AddYears(5);
    if (myDatePlus5Years <= DateTime.Now)
    {
        Console.WriteLine("Greater than or equal to 5 years");
    }
    else
    {
        Console.WriteLine("Less than 5 years");
    }
    
    
    

    Another approach is subtracting 5 years from today's date then comparing to the admission date. Either way, this is a basic addition/subtraction math problem.