ASP   «Prev  Next»

Lesson 7ASP built-in Functions
ObjectiveUse built-in and user-defined functions for data manipulation.

ASP built-in Functions

You will often need to manipulate the values of variables. VBScript provides a number of functions for this purpose, including a Replace function that replaces every occurrence of a substring[1] (word or phrase) in another string with a replacement string.
  • Replace() Function example in ASP
    Replace(variable, searchfor, replacewith)
    

    In this code segment, the word "off" is replaced by the word "around" wherever it is found in the text string stored in the variable cTest. The result can be stored in a new variable or in the original variable.
    <HTML>
      <%	'BEGIN ASP SCRIPT
      Dim cTest, cNew 'Initialize a couple of 'Character variables 
      cTest = "Just showing off the replace statement"
      cNew = Replace(cTest, "off", "around")
      %>          
     <!–END ASP SCRIPT ––>
      The new value is <%=cNew%>.
    </HTML>
    

    The output of this code segment would be:
    The new value is Just showing around the replace statement.
    

    The Trim functions remove leading spaces (LTrim), trailing spaces (RTrim) or both (Trim) from a string. Be aware that different functions work with different types of data.


ASP.NET .NET functionality is available through the `String` class:

In ASP.NET (and .NET in general), the functions `LTrim()`, `RTrim()`, and `Trim()` no longer exist in their original form as they were found in older languages like VBScript. However, in .NET, equivalent functionality is available through the `String` class:
  1. TrimStart(): Equivalent to `LTrim()`. It removes leading white spaces (or other specified characters) from the beginning of the string.
    string example = "   hello";
    string result = example.TrimStart(); // "hello"
    
  2. TrimEnd(): Equivalent to `RTrim()`. It removes trailing white spaces (or other specified characters) from the end of the string.
    string example = "hello   ";
    string result = example.TrimEnd(); // "hello"
    
  3. Trim(): This method still exists and works similarly. It removes both leading and trailing white spaces (or other specified characters) from a string.
    string example = "   hello   ";
    string result = example.Trim(); // "hello"
    

So, while `LTrim()` and `RTrim()` no longer exist as specific functions, their behavior is replicated through `TrimStart()` and `TrimEnd()` respectively. `Trim()` still remains in the API.

In ASP.NET (and the broader .NET ecosystem), the `Date()` and `DateAdd()` functions from Classic ASP have been replaced by more robust and flexible functionality in the `DateTime` structure. Here's how they compare:
  1. Date()` (Classic ASP) - In Classic ASP, `Date()` returns the current system date.
    ASP.NET Equivalent: In ASP.NET, the equivalent functionality is provided by `DateTime.Now.Date`, which returns the current date without the time component.
    DateTime currentDate = DateTime.Now.Date;
    

    If you want both date and time, you can simply use `DateTime.Now`:
    DateTime currentDateTime = DateTime.Now;
    
  2. `DateAdd(argument, value1, value2)` (Classic ASP): In Classic ASP, `DateAdd()` is used to add a specified time interval (such as days, months, years, hours) to a date.
    ASP.NET Equivalent: In ASP.NET, the `DateTime` structure has several methods for adding time intervals, including `AddDays()`, `AddMonths()`, `AddYears()`, `AddHours()`.
    Here are some examples:
    // Adds 5 days to the current date
    DateTime currentDate = DateTime.Now;
    DateTime newDate = currentDate.AddDays(5); 
    
    // Adds 3 months to the current date
    DateTime newDateWithMonths = currentDate.AddMonths(3); 
    
    // Adds 10 hours to the current date
    DateTime newDateWithHours = currentDate.AddHours(10); 
    

In .NET, you don't need to specify an "interval" argument like in Classic ASP (`DateAdd("d", 5, Date())`). Instead, you directly call the appropriate method (e.g., `AddDays()`, `AddMonths()`) based on what you want to add.
Summary:
  • `Date()` in Classic ASP** is replaced by `DateTime.Now` or `DateTime.Now.Date` in ASP.NET.
  • `DateAdd()` in Classic ASP** is replaced by individual methods like `AddDays()`, `AddMonths()`, `AddYears()`, `AddHours()`, etc., on the `DateTime` structure in ASP.NET.


Date and Time Functions in Classis ASP

Two of the most useful Date and Time functions are:
Date()

The Date function returns the current date. The date returned is the date on the server. This value can be stored to a variable and manipulated.
DateAdd(argument,value1,value2)

The DateAdd function adds dates together. It can also be used to increment or decrement a date by an amount in any time or date unit.
Here is the DateAdd function used to add 30 days to the current date:

<HTML>
          .
          .
          .
  <%          'BEGIN ASP SCRIPT
  Dim dCurrDate, dNextMonth          
  'Initialize a couple of date variables
  dCurrDate = Date() 
  'dCurrDate is now equal to today's date
  dNextMonth = DateAdd("d", 30, dCurrDate) 
  'Add 30 days to dCurrDate
  %> 
	<!–END ASP SCRIPT ––>
  The new value is <%=dNextMonth%>.
          .
          .
</HTML>

This MouseOver will give you a line-by-line explanation of how we are using the DateAdd function and what values we need to set in its parameters to add 30 days to the current date.

Dynamic output of date in ASP
Elements of the ASP script
  1. Create and initialize the two variables, dCurrDate and dNextMonth, that we need to perform the calculation.
  2. Use the Date() function for current date to set the value of variable dCurrDate to today's date.
  3. Use the DateAdd function with its parameter set to days, +30 and today's date to count 30 days past today and place the result in our other variable, dNextMonth. Note that the result date may or may not be in the same month as today's date.
  4. Display the new date, 30 days in the future to the user


Date Add Function Example

Numeric functions

Several functions that format a number are available to you. FormatCurrency returns the number with a leading currency symbol. FormatPercent returns the number with a following % symbol and multiplies the value by 100 to create a percentage. FormatNumber returns the number itself with no leading or following characters. The function to format a number as currency has this syntax:

FormatCurrency(expression
  [,NumDigitsAfterDecimal
  [,IncludeLeadingDigit 
  [,UseParensForNegativeNumbers
  [,Groupdigits]]]])

Numeric Functions example

The other numeric functions follow an identical syntax. You can format the same numeric value in different ways and define some additional information on the functions' parameters. The regional settings on the server determine which currency and grouping symbols are returned by the function.
The valid parameter values for
  1. IncludeLeadingDigit,
  2. UseParensForNegativeNumbers, and
  3. GroupDigits are:

0 False/No
-1 True/Yes
-2 Use the server's regional settings (default)


This example assumes the regional setting is United States.
<HTML>
     .
     .
<!-- BEGIN ASP SCRIPT -->
<%  
Response.Write FormatCurrency(1.231,2)  'Outputs $1.23
Response.Write FormatNumber(1.231,2)    'Outputs 1.23
Response.Write FormatPercentage(1.231,2)'Outputs 123.00%
%>
<!–END ASP SCRIPT ––>
     .
     .
</HTML>

Response.Write in this example is a form of ASP's Response object.
For now, just think of it as similar to a PRINT statement in BASIC. We'll cover this in more detail in a future lesson.


The ASP statements and functions in these lessons are just a part of what is available for your Web applications' use through VBScript, which used in legacy Classic ASP environments. User-defined subprocedures and functions let you reuse code you have already written.
With these "mini-programs", you can create generic code that can be easily adapted from use in one Web site to another.


User-defined Subprocedures and Functions

Subprocedures are small groups of code that carry out a specific action, then return control to the calling statement. Creating a sub-procedure is simple: start with "Sub <sub-procedure name>," create the block of code you want to repeat later, then end with "End Sub."
To call the sub-procedure, you use type "Call <sub-procedure name>." Here's an example:
Sub Welcome( )
     Response.Write "Welcome to javadeploy <BR>"
     Response.Write "Date: " & Date & ", Time: " & Time
End Sub

Call Welcome
// (the rest of the page)

  • Functions:
    Functions, unlike sub-procedures, return a value after carrying out an action. This is useful when you need to reuse code, but the data it returns isn't always the same. Creating a function is similar to creating a sub-procedure, except before ending the function, a return value is assigned to the name of the function. This statement sends data back to the calling statement. Here's an example:
    Function DaysLeft(dToday)
    DaysLeft = DateDiff("d", Now(), dToday)
    End Function
        Dim dToday
        dToday="10/05/00"
        Response.Write "Sale ends in " + DaysLeft(dToday)
        & " day(s)."
    

[1]Substring: A portion of a character string (e.g., "shirt" is a substring of "t-shirt").

SEMrush Software