The Essentials of SAS Dates and Times: Derek Morgan, St. Louis, MO
The Essentials of SAS Dates and Times: Derek Morgan, St. Louis, MO
ABSTRACT
The first thing you need to know is that SAS® software stores dates and times as numbers. However, this is not the
only thing that you need to know, and this presentation will give you a solid base for working with dates and times in
SAS. It will also introduce you to functions and features that will enable you to manipulate your dates and times with
surprising flexibility. This paper will also show you some of the possible pitfalls with dates (and times and datetimes)
in your SAS code, and how to avoid them. We'll show you how the SAS System handles dates and times through
examples, including the ISO 8601 formats and informats, how to use dates and times in TITLE and/or FOOTNOTE
statements, and close with a brief discussion of Excel conversions.
That will not get you very far. Depending on the context, you will get an error message telling you that you tried to put
characters into a numeric value, or you will get a character variable with the words, "January 14, 1967" stored in it. It
may look okay, but if you try to do a calculation using that character variable, you will get a missing value.
DATA _NULL_;
date1 = "January 14, 1967";
date2 = "September 4, 2014";
days_in_between = date2 - date1;
PUT days_in_between = ;
RUN;
NOTE: Character values have been converted to numeric values at the places given by:
(Line):(Column). 19 4:27
NOTE: Invalid numeric data, date2='September 4, 2014' , at line 4 column 19.
NOTE: Invalid numeric data, date1='January 14, 1967' , at line 4 column 27.
days_in_between = • (the dreaded missing value dot)
In order to tell SAS about a specific date, you use a "date literal." The date literals for the two dates above are
"14JAN1967"d and "04SEP2014"d. The letter "d" at the end tells SAS that this is a date, not a string of characters, so
the code becomes:
DATA _NULL_;
date1 = "14jan1967"d;
date2 = "04sep2014"d;
days_in_between = date2 - date1;
PUT days_in_between = ;
RUN;
days_in_between=17400
No part of the date literal is case-sensitive, that is, you can use all capital letters, all lower-case, or mixed case for the
date inside the quotes and the 'd' can be upper or lower-case. You may use single or double quotes to enclose the
literal string, but if you use double quotes, you will be subject to macro variable resolution, which means that an
ampersand (&) may cause unexpected results. Time and datetime literals are expressed in a similar fashion;
however, instead of the letter "d", they are followed by the letter "t" for time, or the letters "dt" for datetimes. Time