官术网_书友最值得收藏!

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...
主站蜘蛛池模板: 大安市| 铜川市| 永济市| 北碚区| 衡东县| 兖州市| 清苑县| 兴义市| 浦东新区| 固原市| 大足县| 紫阳县| 滨海县| 巴南区| 清苑县| 赣榆县| 东乌珠穆沁旗| 南康市| 平顺县| 乐清市| 松江区| 武定县| 湘阴县| 轮台县| 南宫市| 来安县| 三都| 彰化市| 伊金霍洛旗| 华阴市| 霞浦县| 塘沽区| 买车| 广州市| 上饶县| 南陵县| 绵竹市| 赤城县| 嘉黎县| 呼图壁县| 庆云县|