DATA Step, Macro, Functions and more

how to convert character MM/YYYY into date format?

Reply
Occasional Contributor
Posts: 6

how to convert character MM/YYYY into date format?

Hello,

 

I would like to convert a character variable (called Month_Year) into a date variable. It has a MM/YYYY format, e.g. 06/1986 corresponds to June 1986.

 

I have tried the following statements but didn't work:

 

informat Month_Year mmyys10.;

Date = input(Month_Year, mmyys10.);

 

Can anyone help?

PROC Star
Posts: 7,364

Re: how to convert character MM/YYYY into date format?

The following will work:

 

data have;
  input cdate $;
  cards;
06/1986
;

data want;
  set have;
  format date date9.;
  date=input(cdate,anydtdte7.);
run;

Art, CEO, AnalystFinder.com

 

Occasional Contributor
Posts: 6

Re: how to convert character MM/YYYY into date format?

Hi art297,

 

Thanks for your reply. Your code works but with a small problem - it added a day value to MM/YYYY.  e.g. it turned 06/1986 into 01JUN1986. Is it possible to convert into a date variable that has only month and year (no day) info in SAS? Does SAS have a date format that only has info on month and year?

 

Thanks again.

PROC Star
Posts: 7,364

Re: how to convert character MM/YYYY into date format?

Occasional Contributor
Posts: 6

Re: how to convert character MM/YYYY into date format?

Thanks!

 

One follow up question - I tried to do this in one statement:

date1=input(date, mmyy10.);

 

but the error message says "The informat MMYY was not fuond or could not be loaded."

 

I ended up having to do this in two statements:

  date1=input(date,anydtdte7.);
  format date1 mmyy10.;

 

Why can't the input function accept mmyy10.?

 

Thanks!!

Super User
Super User
Posts: 6,502

Re: how to convert character MM/YYYY into date format?

[ Edited ]

The assignment statement and the FORMAT statement are doing differnt things. The first is setting the value of a variable and the second is changing the metadata about the variable.

You still need to use a FORMAT statement if you want to attach a format to a variable.

 

There is no INFORMAT named MMYY.  That is why you need to use the ANYDTDTE. informat.

 

Occasional Contributor
Posts: 6

Re: how to convert character MM/YYYY into date format?

Thanks! This makes sense.

Super User
Super User
Posts: 6,502

Re: how to convert character MM/YYYY into date format?

You can't have a date without a day.  You can attach a format that only show the year and the month.

101  data _null_;
102    date = '01JUN1986'd ;
103    do fmt = 'YYMMDD10.','YYMM7.','YYMMS7.','MMYY7.','MMYYS7.';
104       str=putn(date,fmt);
105       put fmt= str= ;
106    end;
107  run;

fmt=YYMMDD10. str=1986-06-01
fmt=YYMM7. str=1986M06
fmt=YYMMS7. str=1986/06
fmt=MMYY7. str=06M1986
fmt=MMYYS7. str=06/1986
Ask a Question
Discussion stats
  • 7 replies
  • 455 views
  • 1 like
  • 3 in conversation