Published on :
Macro CREATION_INTERNE

Managing Numeric Date Conversions with FCMP

This code is also available in: Deutsch Español Français
Awaiting validation
The script includes two FCMP functions: `DateToNum` converts a SAS© date into an integer representing the year, month, and day (YYYYMMDD). `NumToDate` performs the inverse operation, taking a YYYYMMDD integer and transforming it into a valid SAS© date. A concrete example is provided to illustrate their use on a dummy dataset.
Data Analysis

Type : CREATION_INTERNE


The data used for the examples is created directly in the script via a DATA step with `datalines`. The 'test' dataset contains SAS dates and their numeric equivalents to demonstrate the conversion functions.

1 Code Block
DATA STEP Data
Explanation :
This DATA step creates the 'test' dataset with two variables: 'date' (SAS date format) and 'date2' (numeric format). The values are defined via `datalines` to serve as conversion examples.
Copied!
1DATA test;
2 INPUT date date2;
3 informat date date9.;
4 FORMAT date date9.;
5 DATALINES;
6 31DEC2016 20161231
7 01JAN2017 20170101
8 ;
9RUN;
2 Code Block
PROC FCMP
Explanation :
This `PROC FCMP` block compiles the `DateToNum` function. It takes a SAS date (`DateDay`), extracts the year, month, and day, then combines them into a single integer in YYYYMMDD format (for example, 20161231 for December 31, 2016).
Copied!
1PROC FCMP outlib=work.cat_function.test;
2 function DateToNum(DateDay);
3 da = day(DateDay);
4 mo = month(DateDay);
5 ye = year(DateDay);
6 res = (ye * 10000) + (mo * 100) + da;
7 return(res);
8 endsub;
9RUN;
3 Code Block
PROC FCMP
Explanation :
This `PROC FCMP` block compiles the `NumToDate` function. It takes an integer in YYYYMMDD format (`DateNum`), deduces the year, month, and day, and then uses the `mdy` function to convert it into a standard SAS date.
Copied!
1PROC FCMP outlib=work.cat_function.test;
2 function NumToDate(DateNum);
3 ye = int(DateNum/10000);
4 mo = int(DateNum/100)-(ye*100);
5 da = DateNum - (int(DateNum/100) * 100);
6 res = mdy(mo,da,ye);
7 return(res);
8 endsub;
9RUN;
4 Code Block
DATA STEP
Explanation :
This DATA step uses the previously compiled `DateToNum` and `NumToDate` functions. It creates a new variable 'Date2Num' by converting the 'date' variable (SAS date) into numeric format and a 'num2date' variable by converting the 'date2' variable (numeric) into SAS date format.
Copied!
1DATA test;
2 SET test;
3 FORMAT num2date date9.;
4 Date2Num = DateToNum(date);
5 num2date = NumToDate(date2);
6RUN;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
Copyright Info : Creation date : 14/04/2017 (fr) Last update : 14/04/2017 (fr) Author(s) : Nicolas DUPONT