Converting date into internal date type

As already mentioned, regular expressions are useful for converting data into the required format. One good example is the conversion of a date stored in internal format into display format, and vice versa. For example, a date may be available as 20120101 and we need to format it in the form 01/01/2012, and so on. In this recipe, we will see how a single statement of replace may be used to carry out this task. For this recipe, we assum that input date is in the correct internal format.

How to do it...

For carrying out the previously mentioned conversion, proceed as follows:

  1. First, declare a variable mydate having a length of 10 characters. A date having the internal format date is then assigned to this variable. The same variable will be used for storing the converted date.
  2. The replace statement having the regex '(d{4})(d{2})(d{2})' is used, along with the replacement '$3/$2/$1'.
  3. The converted date is then outputted on the screen.
    How to do it...

How it works...

We have used three subgroups in the formation of the regular expression. The d refers to digits and the number given in curly brackets specifies the length of the various date components (4 for year, 2 for month and the date). The three subgroups are specified using parentheses.

Within the replace statement, the subgroup placeholders are used. It specifies the format in which the date is to be outputted (the year followed by a forward slash, then the month, then another forward slash, and finally the date). For the input date, 20120101, following are the values in each of the subgroup registers:

  • Subgroup register 1 denoted by $1: 2012
  • Subgroup register 2 denoted by $2: 01
  • Subgroup register 3 denoted by $3: 01

In this case, the date after the replace statement and the write statement is shown in the following screenshot:

How it works...
..................Content has been hidden....................

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