Chapter 14. Writing Expressions

You can create many reports using data that comes directly from a data source simply by dragging the data set fields from Data Explorer to the report. Sometimes, however, you want to display information that is not in the data source, or you want to display data differently than it appears in the data source. You might also want to sort data using a formula, rather than sorting on an existing field. For these cases, and many others, you write expressions using JavaScript.

An expression is a statement that produces a value. An expression can be a literal value, such as

   3.14
   "It is easy to create reports with BIRT"

When you drag a field into the report, BIRT Report Designer creates the expression for you. The expression specifies the name of the field whose values the report displays. For example, the following expressions get values from the customerName field and the phone field, respectively:

   dataSetRow["customerName"]
   dataSetRow["phone"]

An expression can contain any combination of literal values, fields, operators, variables, and functions, as long as it evaluates to a single value. In the following examples, the first expression combines static text with a field, the second expression uses a JavaScript function, and the third expression multiplies the values of two fields:

   "Order Total: " + row["orderTotal"]
   row["orderDate"].getYear()
   row["itemQuantity"] * row["itemPrice"]

This chapter describes some common uses and examples of expressions in reports. It does not describe all the functions, objects, or operators that you can use in expressions. If you are new to JavaScript, you will find it useful to read a book about JavaScript.

Basic concepts

This section describes some of the basic concepts that you need to understand and remember when writing JavaScript expressions. Understanding these concepts helps you avoid some common mistakes.

Data types

One of the fundamental concepts to understand is data types. Data types are the types of values—numbers, strings, and Booleans, for example—that can be represented and manipulated in any programming language. Every database field has a certain data type, every piece of report data has a certain data type, and every expression that you create returns a value of a particular data type.

This concept is important, because, if the expression that you write does not handle data types properly, you get errors or the results are not what you want. For example, you cannot perform mathematical calculations on numbers if they are of string type, and you cannot convert a date field to uppercase characters.

If you write an expression to manipulate a data set field, verify its type, particularly if the field values are numbers. Numbers can be of string or numeric type. For example, databases typically store zip codes and telephone numbers as strings. Item quantities or prices are always of numeric type so that the data can be manipulated mathematically. IDs, such as customer IDs or order IDs are usually of numeric type so that the data can be sorted in numeric order, such as 1, 2, 3, 10, 11, rather than in alphanumeric order, such as 1, 10, 11, 2, 3.

To see the data type of a field, open the data set in Data Explorer, and choose Output Columns. Output Columns displays the fields in the data set and their types, as shown in Figure 14-1.

Output Columns

Figure 14-1. Output Columns

Case sensitivity

JavaScript is a case-sensitive language. This feature means that a keyword, a function name, a variable name, or any other identifier must always be typed with the correct capitalization. You must, for example, type the getDate( ) function as getDate( ), not as GetDate( ) or getdate( ). Similarly, myVar, MyVar, MYVAR, and myvar are four different variable names.

Data set field names are case sensitive. If you refer to a data set field in an expression, specify the field name with the same capitalization that the data source driver uses to identify the field. As mentioned previously, Output Columns in the data set editor shows the fields. If you use Expression Builder to write an expression, selecting a field to insert in the expression ensures that the correct field name is used.

Multiline expressions

You can write an expression that contains multiple lines, as shown in the following example:

   firstInitial = row["customerFirstname"].charAt(0);
   firstInitial + ". " + row["customerLastname"];

The expression looks like lines of program code, because it is. Expressions can be small pieces of code that do something. The expression in the previous example does the following tasks:

  • It extracts the first character of a string value in a customerFirstname field and assigns the value to a variable named firstInitial.

  • Then, it combines the firstInitial value, a period, a space, and the value in a customerLastname field.

An expression can contain as many lines as you need. Just remember that an expression returns a single value. If an expression contains several lines, it returns the results of the last line. The previous expression returns a value, such as T. Rae.

The lines are called statements, and they are separated from each other by semicolons. If you place each statement on a separate line, as shown in the example, JavaScript allows you to leave out the semicolons. It is, however, good practice to use semicolons to separate statements.

Using Expression Builder

Expression Builder is a tool that you use to create, modify, and view expressions. It provides a list of the objects, functions, and operators that you can include in expressions. Expression Builder is particularly useful when you are learning how to write expressions in JavaScript and discovering which BIRT and JavaScript functions you can use.

Expression Builder is available when you need to specify an expression, such as when you create a computed column in Data Explorer, when you filter data, when you insert a data element, when you specify a data series for a chart, or when you want to display dynamic data in a text element. Figure 14-2 shows Expression Builder.

Expression Builder

Figure 14-2. Expression Builder

You open Expression Builder by choosing one of the buttons that appear in Figure 14-3.

Expression Builder access buttons

Figure 14-3. Expression Builder access buttons

Expression Builder consists of two parts:

  • The top part of Expression Builder is where you create or edit an expression. When you choose objects from the bottom part, they appear in this area. You can also type an expression directly here.

  • The bottom part provides a hierarchical view of the column bindings, report parameters, JavaScript functions, BIRT functions, operators, and data set fields that you can select to build an expression. The items that appear under Category vary, depending on the context of the expression. When you select an item in Category, its contents appear in Sub-Category. When you select an item in Sub-Category, its contents—which you insert in an expression—appear in the box that is the farthest to the right. Figure 14-4 shows an example.

Functions for String class

Figure 14-4. Functions for String class

Table 14-1 provides detailed descriptions of the items in Expression Builder’s Category column.

Table 14-1. Categories in Expression Builder

Item

Description

Available Column Bindings

Displays the column bindings—references to data set fields—that are available to the current report element. An element can access column bindings that are defined on the element itself and on the element’s container.

Report Parameters

Displays the report parameters that you created using Data Explorer. Report parameters are typically used to get input from users when they run the report.

Native JavaScript Functions

Displays native JavaScript functions by objects, such as String, Date, Math, and so on. Use these functions to manipulate or calculate data.

For summary information about a function, hover the mouse over the item to display a ToolTip. For detailed information, see a JavaScript book.

BIRT Functions

Displays the JavaScript functions that are defined by BIRT. The functions are categorized in these objects: DateTimeSpan, Finance, and Total. Use these functions to calculate data.

For summary information about a function, hover the mouse over the item to display a ToolTip. For detailed information, see “Scripting Reference” in BIRT’s online help.

Operators

Displays types of JavaScript operators, such as Assignment, Comparison, Computational, and Logical.

Available Data Sets

Displays the data set or data sets that are available to the current report element. Expand the data sets to select fields to use in an expression. You can access data set fields only when you create a column-binding expression or when you create a computed field in the data set editor.

Manipulating numeric data

Numeric data is probably the most commonly manipulated type of data. Expressions can perform a basic operation, such as multiplying a price field by a quantity field to calculate an extended price, or more complex calculations, such as a financial calculation that returns the depreciation value of an asset. You can use functions to calculate aggregate information, such as totals, averages, medians, modes, and so on, as discussed in Chapter 13, “Aggregating Data.”

Both JavaScript and BIRT provide a wide range of functions for manipulating numeric data. In Expression Builder, look under Native JavaScript Functions—Number and Math and under BIRT Functions—Total and Finance. The following sections describe common number-manipulation tasks and provide examples of expressions.

Computing values from multiple numeric fields

If your report primarily displays values from numeric fields, it most likely contains computed values as well. An invoice, for example, typically shows the following computed values:

  • Extended prices that display the result of unit price * quantity for each line item

  • Sales tax total that displays the sum of extended prices * tax rate

  • Invoice total that displays the sum of extended prices + shipping + sales tax

Order of precedence

When a calculation involves more than two numbers and different operators, remember the order of precedence, which is the order in which operators are evaluated. Consider the following math expression:

   55 + 50 + 45 * 2

If you did each operation from left to right in these steps:

   55 + 50 = 105
   105 + 45 = 150
   150 * 2 = 300

Your answer would be 300.

If you specify the math expression in a data element, BIRT Report Designer returns 195, which is the correct answer. The difference in answers lies in the order of precedence. This concept is one that you might remember from math class. Multiplication and division are evaluated first from left to right across the expression. Then, addition and subtraction are evaluated from left to right across the expression. Using the previous example, the expression is evaluated as follows:

   45 * 2 = 90
   55 + 50 = 105
   105 + 90 = 195

If you want the addition performed first, instead of the multiplication, enclose the addition part within parentheses, as follows:

   (55 + 50 + 45) * 2

The following list describes examples of expressions that compute values from multiple numeric fields.

  • The following expression calculates a total price after deducting a discount and adding an 8% tax that applies to the discounted price:

       (row["extendedPrice"] - row["discount"]) +
          (row["extendedPrice"] - row["discount"]) * 0.08
  • The following expression calculates an invoice total, which includes the total of all extended prices, an 8% sales tax, and a 10% shipping and handling charge:

       Total.sum(row["extendedPrice"]) +
          (Total.sum(row["extendedPrice"]) * 0.08) +
          (Total.sum(row["extendedPrice"]) * 0.10)
  • The following expression calculates a gain or loss in percent:

       (row["salePrice"] - row["unitPrice"])/row["unitPrice"] * 100

Division by zero

If you divide the value of one numeric field by another and the denominator value is 0, the result is infinity (∞).

For example, if the following expression:

   row["total"]/row["quantity"]

evaluates to:

   150/0

the data element that contains the expression displays ∞.

The return value is infinity, because dividing a number by zero is an operation that has no answer. Mathematicians consider this operation undefined, illegal, or indeterminate.

If you do not want the infinity symbol to appear in the report, you can replace it with a string value, such as Undefined, or replace it with an empty string (“”) to display nothing. The infinity symbol is a numeric value, therefore, you must convert it to a string before replacing it with a different string.

The following expression replaces ∞ with Undefined:

   // Convert number to a string
   x = row["total"]/row["quantity"] + ""
   // Replace ∞ with the word Undefined
   x.replace("Infinity", "Undefined")

Converting a number to a string

You can convert a number to a string using one of the following techniques:

  • Use the JavaScript toString( ) function

  • Add an empty string (“”) to the number

The following expressions yield the same result. If the value of orderID is 1000, both expressions return 10005.

   row["orderID"].toString( ) + 5
   row["orderID"] + "" + 5

Any time that you combine a literal string with a number, JavaScript converts the number to a string. Be aware of this fact, especially if you want to also manipulate the number mathematically. For example, the following expression changes orderID to a string:

   "Order ID: " + row["orderID"]

If you want to perform a calculation and also add a literal string, do them in separate steps. Perform the calculation first, then append the string, as shown in the following example:

   orderIDvar = row["orderID"] + 10;
   "Order ID: " + orderIDvar;

If the value of orderID is 1000, the expression returns:

   Order ID: 1010

Manipulating string data

Often, a data source contains string or text data that is not in the right form for your reporting needs. For example, you want to sort a report by last name, but the data source contains last names only as part of a full name field. Or, conversely, you want to display full names, but the data source stores first names and last names in separate fields.

JavaScript provides a wide range of functions for manipulating strings. In Expression Builder, look under Native JavaScript Functions—String. The following sections describe some of the common string-manipulation tasks and provide examples of expressions.

Substituting string values

Sometimes, you need to substitute one string value for another. Perhaps data was added to the data source inconsistently. For example, some addresses contain “Street,” and some contain “St.” You can replace entire string values or just parts of a string by using the replace( ) function in JavaScript.

The replace( ) function searches for a specified string and replaces it with another string. It takes two arguments: the string to replace, and the new string. The following expression searches for “St.” in an address field and replaces it with “Street.”

   row["address"].replace("St.", "Street")

What if you need to search for and replace multiple strings in a single field? Add as many replace( ) functions as you need to the expression, as shown in the following example:

   row["address"].replace("St.", "Street").replace("Ave.",
      "Avenue").replace("Blvd", "Boulevard")

As with any global search-and-replace operation, be aware of unintended string replacements. For example, the row[“address”].replace(“St.”, “Street”) expression replaces St. Mary Road with Street Mary Road. In this case, rather than just searching for “St.”, you need to search for “St.” at the end of a line. To specify this type of search, you need to specify a string pattern to search, rather than a literal string. For more information about searching for patterns, see “Matching string patterns,” later in this chapter.

If you need to replace entire strings, rather than just a part of the string, you can use the mapping feature instead. The mapping feature is ideal for replacing known sets of values. For example, a gender field contains two values, M or F. You can map the M value to Male, and F to Female. For more information about mapping values, see “Specifying alternate values for display” in Chapter 11, “Formatting Report Content.”

Combining values from multiple fields

Each field in a database often represents a single piece of information. A customer table, for example, might contain these fields: customerFirstname, customerLastname, addressLine_1, addressLine_2, city, state, zip, and country.

You can create a customer report that uses data from all these fields by dragging each field to a table cell. The generated report, however, does not look professional, because the space between each piece of data is uneven, as shown in Figure 14-5. The spacing is uneven because the size of each table column adjusts to fit the longest string.

Report with separate field values

Figure 14-5. Report with separate field values

The solution is to combine, or concatenate, the first and last names and place the concatenated name in a single table cell. Similarly, concatenate all the address-related fields and place the full address in a single table cell. In JavaScript, you concatenate string values using the + operator.

For the name, add a literal space (“ ”) between the name fields so that the first and last name values do not run together. For the address, add a comma and space between all the fields, except between state and zip. For these fields, add only a space between them.

For this example, you would use the following expressions:

   row["customerFirstname"] + " " + row["customerLastname"]

   row["addressLine1"] + ", " + row["addressLine2"] + ", " +
      row["city"] + ", " + row["state"] + " " + row["zip"] + ", "
      + row["country"]

The report now looks like the one shown in Figure 14-6.

Report with combined field values

Figure 14-6. Report with combined field values

Several addresses display the word null, because the addressLine2 field contains no data. In a database, a null value means no value was supplied. In cases where you concatenate fields that might contain no data, you need to remove the word null from the returned string value. This task is described in the next section.

Removing null values from combined fields

When you concatenate string values, JavaScript converts null values to the word null. The example report in the previous section displayed addresses with the word null when the addressLine2 field did not contain a value, for example:

   8490 Strong St., null, Las Vegas, NV 83030, USA

You can remove the word null by using the replace( ) function. In this example, use replace( ) in the expression to search for “null,” and replace it with an empty string. You should also search for the comma and space after null to remove the extra comma and space that is added after the addressLine2 field. If you search only for “null” you get the following results:

   8490 Strong St., , Las Vegas, NV 83030, USA

You use the following expression to remove null values from a concatenated address:

   (row["addressLine1"] + ", " + row["addressLine2"] + ", " +
      row["city"] + ", " + row["state"] + " " + row["zip"] + ", "
      + row["country"]).replace("null, ","")

Searching for and replacing “null,” does not, however, take into account missing values in the state and country fields. The state value does not have a comma after it, so you need to search for “null”. The country value does not have a comma or space after it, so you need to search for “null”.

To replace null values in the state and country fields, add two more replace( ) functions to the expression:

   (row["addressLine1"] + ", " + row["addressLine2"] + ", " +
       row["city"] + ", " + row["state"] + " " + row["zip"] + ", "
       + row["country"]).replace("null, ","").replace("null ","")
       .replace("null","")

Getting parts of a string

Sometimes, you want to display only a portion of a string. For example:

  • An address field stores a full address, but you want to display only the zip code or the state.

  • A name field stores a full name, and you want only the first or last name.

  • An e-mail field stores e-mail addresses, and you want only the user name that precedes the @ symbol.

Depending on the content of the string and which part of a string you need—the first part, the last part, or a part after or before a particular character—the expression that you specify varies. The JavaScript functions that you are likely to use in the expression include the functions shown in Table 14-2.

Table 14-2. Getting information about a string

JavaScript

Use to

charAt( )

Get the character at the specified position of a string. Note that in JavaScript, the first character starts at 0, not 1.

indexOf( )

Find the first occurrence of a specified character and return its position in the original string.

lastIndexOf( )

Find the last occurrence of a specified character and return its position in the original string.

length

Get the length of a string. Note that length is a property of a string, not a function, so you do not use parentheses, ( ), after the keyword, length.

substr( )

Return a substring of a specified length, starting from a particular position in the original string.

The following examples show how to get different parts of a string. Assume a customerName stores names in first name and last name format, such as Robert Allen.

  • To get the first name:

    • Use indexOf( ) to get the position of the space character that separates the first name from the last name.

    • Use substr( ) to get the first name, starting from the first character and for a specified length. The first character for JavaScript starts at 0, not 1. The length that you need to specify is equal to the position of the space character, and not the position of the space character minus 1, as you might think. Consider the name Robert Allen. Logically, the space between the first and last names is the seventh character, but JavaScript counts its position as six. To return the first name, Robert, excluding the space, you want substr( ) to return six characters.

    The following expression returns the first name:

       spaceCharPosition = row["customerName"].indexOf(" ");
       newStringtoDisplay =
          row["customerName"].substr(0, spaceCharPosition);
  • To get the last name, you use indexOf( ) and substr( ) again. The difference is the arguments that you specify for substr( ). To get the last name, you want to start from the character after the space, and the number of characters that you want is the length of the entire string minus the length up to the space.

    The following expression returns the last name:

       spaceCharPosition = row["customerName"].indexOf(" ");
       newStringtoDisplay =
          row["customerName"].substr(spaceCharPosition + 1,
          row["customerName"].length - spaceCharPosition);
  • To get the first name initial and the last name to display, for example, R. Allen:

    • Use the expression in the previous example to get the last name.

    • Add a statement that gets the first letter in the customerName field. You can use substr(0,1) to get only the first character. You can also use charAt(0), which returns a character in a specified position of a string.

    • Add a statement to combine the first name initial, a period, a space, and the last name.

      The following expression returns the first name initial and last name:

         firstNameInitial = row["customerName"].charAt(0);
         spaceCharPosition = row["customerName"].indexOf(" ");
         lastName = row["customerName"].substr(spaceCharPosition + 1,
            row["customerName"].length - spaceCharPosition);
         newStringtoDisplay = firstNameInitial + ". " + lastName;

Matching string patterns

The previous section described some techniques for getting parts of a string for display. Sometimes you need to match patterns, rather than literal substrings, in string values. You can, for example, use pattern-matching to

  • Filter rows to display only customers whose last names start with a particular string pattern.

  • Search for string patterns, using wildcard characters, and replace with a different string.

To perform pattern-matching, you use regular expressions. A regular expression, also known as regexp, is an expression that searches for a pattern within a string. Many programming languages support regular expressions for complex string manipulation. JavaScript regular expressions are based on the regular expression features of the Perl programming language with a few differences.

In JavaScript, a regular expression is represented by the RegExp object, which you create by using a special literal syntax. Just as you specify a string literal as characters within quotation marks, you specify a regular expression as characters within a pair of forward slash (/) characters, as shown in the following example.

   var pattern = /smith/;

This expression creates a RegExp object and assigns it to the variable pattern. The RegExp object finds the string “smith” within strings, such as smith, blacksmith, smithers, or mark smith. It would not match Smith or Mark Smith, because the search is case sensitive.

You can perform complex pattern-matching by using any number of special characters along with the literal string to search for, as shown in Table 14-3.

Table 14-3. Examples of regular expressions

Regular expression

Description

   /y$/

Matches any string that contains the letter “y” as its last character. The ^ flag specifies that the character to search is at the end of a string.

 

Matches: Carey, tommy, johnny, Fahey.

 

Does not match: young, gayle, faye.

   /^smith/i

Matches any string that starts with “smith”. The $ flag specifies that the string to search is at the beginning of a string. The i flag makes the search case insensitive.

 

Matches: Smith, smithers, Smithsonian.

 

Does not match: blacksmith, John Smith

   /go*d/

Matches any string that contains this pattern. The asterisk (*) matches zero or any number of the character previous to it, which is “o” in this example.

 

Matches: gd, god, good, goood, goodies, for goodness sake.

 

Does not match: ged, gored.

   /go?d/

Matches any string that contains this pattern. The question mark (?) matches zero or one occurrence of the character previous to it, which is “o” in this example.

 

Matches: gd, god, godiva, for god and country.

 

Does not match: ged, gored, good, for goodness sake.

   /go.*/

Matches any string that contains “go” followed by any number of characters. The period (.) matches any character, except the newline character.

 

Matches: go, good, gory, allegory

   /Ac[eio]r/

Matches any string that contains “Ac” followed by either e, i, or o, and r.

 

Matches: Acer, Acir, Acor, Acerre, National Acer Inc.

 

Does not match: Aceir, Acior, Aceior.

There are many more special characters you can use in a regular expression, too many to summarize in this section. In addition, the RegExp object provides several functions for manipulating regular expressions. If you are familiar with regular expressions in other languages, note that some of the syntax of JavaScript regular expressions differs from the syntax of Java or Perl regular expressions. Most notably, JavaScript uses forward slashes (/ /) to delimit a regular expression, and Java and Perl use double quotation marks (“ ”).

Using pattern-matching in filter conditions

In BIRT Report Designer, regular expressions are particularly useful when creating filter conditions. For example, a filter condition can contain a regular expression that tests whether the value of a string field matches a specified string pattern. Only data rows that meet the filter condition are displayed. You can, for example, create a filter to display only rows where a memo field contains the words “Account overdrawn”, where a customer e-mail address ends with “.org”, or where a product code starts with “S10”.

When you use the filter tool in BIRT Report Designer to specify this type of filter condition, use the Match operator, and specify the regular expression, or string pattern, to match. Figure 14-7 shows an example of specifying a filter condition that uses a regular expression.

Example of regular expression

Figure 14-7. Example of regular expression

In this example, the filter condition is applied to a table in the report design. In the generated report, the table displays only customers whose names contain the word National.

Using pattern-matching to search for and replace string values

So far, this chapter has described some of the syntax that is used to create regular expressions. This section discusses how regular expressions can be used in JavaScript code to search for and replace string values. Recall that in “Substituting string values,” earlier in this chapter, we used replace( ) to search for a specified string and replace it with another.

Sometimes, you need the flexibility of searching for a string pattern rather than a specific string. Consider the example that was discussed in that earlier section.

The row[“address”].replace(“St.”, “Street”) expression replaces St. Mary Road with Street Mary Road. To avoid these types of erroneous search-and-replace actions, use the following expression to search for “St.” at the end of a line. The $ flag specifies a match at the end of a string.

   row["address"].replace (/St.$/, "Street")

Consider another example: In your report, you display the contents of a memo field. You notice that in the content, the word JavaScript appears as javascript, Javascript, and JavaScript. You want JavaScript to appear consistently in the report. To do so, you can write the following expression to search for various versions of the word and replace them with JavaScript:

   row["memoField"].replace("javascript",
      "JavaScript").replace("Javascript", "JavaScript")

This expression searches for the specified strings only. It would miss, for example, JAVASCRIPT or javaScript. You can, of course, add as many versions of the word you can think of, but this technique is not efficient.

An efficient and flexible solution is to use a regular expression to search for any and all versions of JavaScript. The following expression replaces all versions of JavaScript with the correct capitalization, no matter how the word is capitalized:

   row["memoField"].replace(/javascript/gi, "JavaScript")

The g flag specifies a global search, which means that all occurrences of the pattern are replaced, not just the first. The i flag specifies a case-insensitive search.

Converting a string to a number

A data source can store numbers as strings. Telephone numbers, zip codes, user IDs, and invoice numbers are some of the numbers that might be stored as strings. If you want to manipulate these numbers mathematically, you need to convert them to numeric type using the parseInt( ) or parseFloat( ) JavaScript function. The following example converts an invoice ID to an integer and adds 10 to it:

   parseInt(row["invoiceID"]) + 10

If the invoiceID is 1225, this expression returns 1235. If you did not convert invoiceID to a real number, the result of adding 10 to invoiceID is 122510.

Manipulating date-and-time data

Both JavaScript and BIRT provide a wide range of functions for manipulating dates. In Expression Builder, look under Native JavaScript Functions—Date, and under BIRT Functions—DateTimeSpan. The following sections describe some of the common date-manipulation tasks and provide examples of expressions.

Displaying the current date

Reports typically display the date on which it is generated, so that users can tell if the data in the report is up-to-date. To display the current date, use the following expression in a data element:

   new Date( )

When the report is run, the current date appears in the format that is determined by the locale setting on the user’s system. If, for example, the locale is English (United States), the date appears as follows:

   6/18/05 12:30 PM

If you want to display the date in a different format, such as June 18, 2005, use Property Editor to set the data element’s Format DateTime property to the desired format.

Getting parts of a date or time as a number

You can use the JavaScript date functions, such as getDay( ), getMonth( ), and getYear( ), to get the day, month, or year of a specified date field. Similarly, with the getHours( ), getMinutes( ), and getSeconds( ) functions, you can get the hour, minute, or second of a specified time field. All these functions return values as numbers. For example, getDay(row[“orderDate”]) returns 1 for a date that falls on Monday. Except for getDate( ), which returns the day of the month, the range of return values for the other functions start at 0. The return values for getMonth( ), for example, are between 0, for January, and 11, for December. Similarly, getDay( ) returns 0 for Sunday and 6 for Saturday.

If you want to display parts of a date in a different format, for example, display the month as a word such as January, February, and so on, use Property Editor to set the data element’s Format DateTime property to the desired format.

Calculating the time between two dates

It is often useful to calculate and display the number of days, months, or years between two dates. For example, a data source might store two dates for each order record—the date on which the order was placed and the date on which the order was shipped. To provide information about order fulfillment trends, you can use BIRT’s DateTimeSpan functions to calculate and display the number of days between the order date and the ship date:

   DateTimeSpan.days(row["orderDate"], row["shippedDate"])

You can also display the number of hours between the two dates, using the following expression:

   DateTimeSpan.hours(row["orderDate"], row["shippedDate"])

Use a different DateTimeSpan function, depending on the range of time between two dates. For example, you would not use DateTimeSpan.month( ) to calculate the amount of time between order dates and ship dates, because, if orders are usually shipped within two weeks, DateTimeSpan.month( ) will often return 0.

Calculating a date

You can add or subtract a specified amount of time to or from a date to calculate a new date. For example, the following information is stored for each order record: the date on which the order was placed and the shipment time in days. You want to calculate the date that customers can expect to receive their orders. Given those two fields, you can calculate the new date by adding the number of shipping days to the date on which the order was placed. You use BIRT’s DateTimeSpan.addDate( ) function to calculate the new date. addDate( ) takes four arguments: the starting date, the number of years, the number of months, and the number of days.

The following expression shows how to calculate the expected delivery date:

   DateTimeSpan.addDate(row["orderDate"], 0, 0, row["shipTime"])

Another function that you can use to calculate a new date is DateTimeSpan.subDate( ). Use this function to subtract days, months, or years to arrive at a new date. It takes the same four arguments as addDate( ).

Using Boolean expressions

A Boolean expression returns one of two values: true or false. The following expressions are basic Boolean expressions:

   row["sales"] > 5000
   row["state"] == "CA"
   row["orderDate"] >= "03/01/2006"

In the first expression, the sales value is tested to be greater than 5000. If the value is greater than 5000, the expression returns true. If it is not, the expression returns false.

In the second expression, the state value is tested for CA. If the value is CA, the expression returns true; if not, the expression returns false. For Boolean expressions, you must use comparison operators. As the second expression shows, you use ==, not the assignment operator, =. The expression row[“state”] = “CA” returns CA. It does not return a true or false value.

In the third expression, the order date is tested to be greater or equal to 03/01/2006. The date value that you enter depends on your machine’s locale. You must enclose the date value in double quotation marks (“”).

A Boolean expression can be as complex as you need. It can contain a combination of And (&&) and Or (||) operators, along with the comparison operators. The following expressions are examples of complex, or compound, Boolean expressions:

  • The following expression returns true if an order total is greater than or equal to 5000 and an order ID is greater than 2000. Both conditions must be true.

       row["orderTotal"] >= 5000 && row["orderID"] > 2000
  • The following expression returns true if the state is CA or WA. Only one condition needs to be true.

       row["state"] == "CA" || row["state"] == "WA"
  • The following expression returns true if three conditions are true:

    • The state is CA or WA.

    • The order total is greater than 5000.

    • The order ID is greater than 2000.

         (row["state"] == "CA" || row["state"] == "WA") &&
            (row["orderTotal"] > 5000 && row["orderID"] > 2000)

    You use a Boolean expression to:

  • Conditionally display a report element.

  • Specify conditions with which to filter data.

  • Specify conditions with which to perform particular tasks. You can, for example, use a Boolean expression in an if statement to do something when the expression is true and to do something else when the expression is false.

       if (row["creditScore"] > 700) {
          displayString = "Your loan application has been
          approved."
          }
       else{
          displayString = "Your loan application has been denied."
          }

    You seldom use a Boolean expression on its own unless you want to display true or false in the report.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.15.99