SAS Functions

Create Date Variables in SAS with the MDY Function

Date Variables in SAS

SAS stores all dates variables as numbers with the 1st of January 1960 as zero. So, for example, New Years Day 2020 is day number 21915 in SAS. This article explains how you can create date variables in SAS with the MDY function.

The MDY syntax

MDY(month, day, year)

The MDY (Month Day Year) function contains three obligatory arguments:

  • month: The month of the date you want to create.
  • day: The day of the date you want to create.
  • year: The year of the date you want to create. This argument can be two or four digits long. However, it’s recommended to use the four-digit format to avoid confusion.

All arguments can be constants or variables. In the next section, you find examples of both possibilities.

SAS Code & Examples

Below you find some examples of how to create SAS date variables with the MDY function. In the first example, we create a simple date variable where the arguments are constants. The date we create is the 20th of June 2020.

data work.ds_mydate;
	my_date = mdy(6, 20, 2020);
	
	format my_date date9.;
run;
MDY with constant arguments

In the next example, we create some dates where the arguments are existing columns.

data work.ds;
	input month day year;
	datalines;
1 1 2020
6 7 2020
12 31 2020
7 14 2020
;
run;

data work.ds_mdy;
	set work.ds;
	
	my_date = mdy(month, day, year);
	
	format my_date date9.;
run;
MDY input data set
MDY output data set

In the last two examples, we demonstrate how to create a date variable with today’s date and how to use the DHMS function to convert Date variables into Date Time variables.

data work.ds_today;
	my_today = today();
	
	format my_today date9.;
run;

data work.ds_my_datetime;
	set work.ds_today;
	
	my_datetime = dhms(my_today, 18, 30, 0);
	
	format my_datetime datetime20.;
run;
SAS TODAY function
SAS DHMS function

Keep in mind that both Date and Date Time variables in SAS are numbers. So, to make them interpretable you need to format them. For example, with the date9. format or the datetim20. format.

You can find the official SAS documentation about the MDY function here.

This useful online tool converts Date (Time) variables into a number. This can be handy when you work with macro variables.

One thought on “Create Date Variables in SAS with the MDY Function

Comments are closed.