Francesco
Francesco

Reputation: 3

SAS: importing different format dates within same variable

I'm trying to import a variable (called bdate) containing dates expressed as YYYYMM or YYYYMMDD formats. Given that I have to import many files with the same problem, I tryed to create my own format (called date) throw PROC FORMAT statement.

PROC FORMAT; 
     value date
     0 - 999999 = [YYMMN6.]
     1000000 - 99999999 = [YYMMDD10.]; run;

The log didn't show any error messages but my own format didn't work when I tried to use it for bdate variable importation:

data example;
infile ....;
        informat bdate best10. ;
        format bdate date10. ;
        run;

How can I fix this problem?

Upvotes: 0

Views: 292

Answers (2)

Tom
Tom

Reputation: 51566

Why not just read it into a character variable first and then apply the right informat based on the length?

data test ;
  input chardate $ ;
  if length(chardate)=6 then date=input(chardate,YYMMN6.);
  else if length(chardate)=8 then date=input(chardate,YYMMDD8.);
  format date yymmdd10. ;
  put chardate= date= ;
cards;
201601
20160125
;

Upvotes: 0

user667489
user667489

Reputation: 9569

You need to define an informat, not a format. Formats are for displaying data, and informats are for importing data. It just so happens that a lot of built-in SAS date formats have equivalent informats and vice versa, so the distinction isn't obvious at first, until you start defining your own.

PROC FORMAT; 
     invalue mydate
     0 - 999999 = [YYMMN6.]
     1000000 - 99999999 = [YYMMDD10.]; 
run;

data _null_;
  do i = 201601,20160102;
    j = input(i,mydate.);
    put j yymmdd10.;
  end;
run;

Upvotes: 2

Related Questions