Juddson Ivines
Juddson Ivines

Reputation: 63

Comparing dates with a function if/else statement

I'm a relatively new web developer who has recently inherited a client web site that features the following code:

<%
    If objDbRs("Accred_Date") <> "" Then
    dim dateAcc, dateAccEnd
    dateAcc = formatDateTime(objDbRs("Accred_Date"),vbshortdate)
    dateAccEnd = DateAdd("yyyy",5,dateAcc)

    Response.write dateAcc & " to " & dateAccEnd
Else
    Response.write "<em>Accreditation information not available.</em>"
End If
%>

It simply displays a given profile's sign up date and an expiration date coded for 5 years later. The client has asked my company to change this automated expiration date to 3 years later, rather than 5. However, this should only affect the profiles that were added on or after June 1, 2016, leaving all of the older profiles grandfathered in for 5 years.

I am not immediately familiar with this code or its syntax and was hoping to get some help in resolving this issue. If someone could show me what code adjustments are necessary to accomplish this objective AND provide a useful syntax reference source for this language, so that I can better handle similar client requests in the future, I'd greatly appreciate it.

Upvotes: 2

Views: 727

Answers (1)

user692942
user692942

Reputation: 16682

This should do what you are asking but it's worth trying to understand how the modifications here change the above code to do what you have asked.

<%
Dim dateAcc: dateAcc = objDbRs("Accred_Date") & ""
Dim dateAccEnd, NumOfYears

If dateAcc <> "" Then
    dateAcc = CDate(dateAcc)
    'Check if the Account was created on / after 1st June 2016
    'Set value of NumOfYears accordingly.
    If dateAcc >= DateSerial(2016, 6, 1) Then
        NumOfYears = 3
    Else
        NumOfYears = 5
    End If
    'Add number of years based off NumofYears to End Date.
    dateAccEnd = DateAdd("yyyy", NumOfYears, dateAcc)
    'Only string format the date after checking it.
    dateAcc = FormatDateTime(dateAcc, vbShortDate)
    dateEnd = FormatDateTime(dateEnd, vbShortDate)
    Response.write dateAcc & " to " & dateAccEnd
Else
    Response.write "<em>Accreditation information not available.</em>"
End If
%>

The Account Expiration is being controlled by this line

dateAccEnd = DateAdd("yyyy", NumOfYears, dateAcc)

by substituting the hard coded value of 5 we can pass a variable (NumOfYears) that is defined by whether the account was created on or after 1st June 2016 (used DateSerial() for this, which takes a date of a series of numeric values, year, month and day).

There are better ways of structuring this but wanted to keep it simple for now. For example hardcoding DateSerial(2016, 6, 1) is a bad idea and makes it more cumbersome to manage the code, ideally that should be passed in either from another source (config, database etc) or at the very least stored as a Constant value.


Useful Links

Upvotes: 1

Related Questions