BookmarkSubscribeRSS Feed
marleeakerson
Calcite | Level 5

Hello, 

 

I am trying to extract the month from a date value that looks like this 

 

Date1

20080201

20080301

20080401

 

and I want to create a new variable that is 

 

Date2

02

03

04 

 

So i tried using 

Date2=SUBSTR(Date1, 5, 2);

 

But it did not work. Can you help?

 

 
6 REPLIES 6
tomrvincent
Rhodochrosite | Level 12
Put Date1 into a char variable before you substr.
marleeakerson
Calcite | Level 5

How do I do that? 

tomrvincent
Rhodochrosite | Level 12
To convert numeric values to character, use the PUT function
PeterClemmensen
Tourmaline | Level 20

phrases like 'it did not work' does not help us much. What differs from what you expect? What does the log say?

 

Help us help you 🙂

Tom
Super User Tom
Super User

Do you have a character variable?  Or a numeric?  If a numeric does it have date values? Or just numbers like 20,200,801?

data have;
  input
   @1 date yymmdd8.
   @1 char $8.
   @1 num 
  ;
  format date yymmdd10.;
cards;
20080201
20080301
20080401
;

data want;
  set have;
  month_date = month(date);
  month_char = substr(char,5,2);
  month_num = int(mod(num,1E4)/1E2);
run;
                                             month_    month_    month_
Obs          date      char         num       date      char       num

 1     2008-02-01    20080201    20080201       2        02         2
 2     2008-03-01    20080301    20080301       3        03         3
 3     2008-04-01    20080401    20080401       4        04         4

In general it is easier/clearer to work with actual date values.  So perhaps you want to convert character or non-date numerics to date first.

 

data want;
  set have;
  month_date = month(date);
  month_char = month(input(char,yymmdd8.));
  month_num = month(input(put(num,z8.),yymmdd8.));
run;