BookmarkSubscribeRSS Feed
marleeakerson
Calcite | Level 5

I am trying to extract the year from a date variable (in the dataset as MM/DD/YYYY). But every time I use the substr statement, I get random numbers that are not even in the date variable at all. I first converted the original date variable from the number of days passed from Jan 1,1960 format to the MM/DD/YYYY format so i am wondering if that is contributing to it. 

 

Thank you! 

 

data want;
set have;
Year=substr(Date,7,4);
run;
4 REPLIES 4
Reeza
Super User
How did you do that conversion?
Why not just use the YEAR() function on the original variable?

data want;
set have;
year = year(origDate);
run;
VDD
Ammonite | Level 13 VDD
Ammonite | Level 13

leave the date the way it was if Date is a valid SAS date.

then do something like this:

 

data temp;
sasdate = "10NOV2009"d;
day = day(sasdate);
month = month(sasdate);
year = year(sasdate);
format sasdate date9.;
run;
  
proc print data = temp;
run;
novinosrin
Tourmaline | Level 20

HI @marleeakerson  First things to note:

 

1. Is your data a SAS date numeric variable that is just formatted for display with some format?

2. If not, is it properly left aligned character variable(though not important, improves sanity checks)

3. run a proc contents and proc print with obs=10 records to know and see what the data(date variable) really is

 

The above 3 will lead us to next steps

Tom
Super User Tom
Super User

@marleeakerson wrote:

I am trying to extract the year from a date variable (in the dataset as MM/DD/YYYY). But every time I use the substr statement, I get random numbers that are not even in the date variable at all. I first converted the original date variable from the number of days passed from Jan 1,1960 format to the MM/DD/YYYY format so i am wondering if that is contributing to it. 

 

Thank you! 

 

data want;
set have;
Year=substr(Date,7,4);
run;

You need to show your data.  If DATE is a character string like '10/03/2019'  then you are asking for characters number 7 thru 10 which would be '2019'.  If DATE is number with the MMDDYY10. format attach to it then it will first be converted to a character string using the BEST12. format.  So '03OCT2019'd would be converted to: 

"       21825"

And then the 7th to 10th characters would be " 218".

 

So you want a number out? 

year=year(date);

Or a string?

year=put(year(date),4.);

sas-innovate-wordmark-2025-midnight.png

Register Today!

Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.


Register now!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 4 replies
  • 805 views
  • 0 likes
  • 5 in conversation