BookmarkSubscribeRSS Feed
kkwan
Calcite | Level 5

I have a variable "date"

 

In most instances the date is reported as "YYYYMMDD" but in some instances the day is missing, so I only have "YYYYMM"

I ultimately want a date variable which looks like "MM/DD/YYYY"

 

I know that if everything in the original date variable was "YYYYMMDD" then I could do:

 

new_date = input(put(date,8.),yymmdd8.);
format new_date mmddyy10.;

 

But since some "date" values are only 6 characters long it's throwing up error signs. I figure that if the date is missing I'll set the day to the first of the month.

 

How could I set dates which only have a length of 6 to have a day value of "01" added to the end? I should be able to convert the new "YYYYMMDD" variable to "MM/DD/YYYY" myself afterwards.

 

Thanks in advance

2 REPLIES 2
biopharma
Quartz | Level 8

One way to trick this is to define a character variable that does not hold any more than 10 spaces to fully accommodate YYYY-MM-DD. Then you can append "-01-01". Only partial dates will be able to add the extra values. 

 

 

data have ;
  length havedateC $15 ;
  havedateC = "2020-05-29" ;
  output ;
  havedateC = "2020-05" ;
  output ;
  havedateC = "2020" ;
  output ;
run ;

data want ;
   set have ;
   length fulldateC $10 ;
   fulldateC = strip(havedateC)||"-01-01" ;
   fulldateN = input(fulldateC,yymmdd10.) ;
   format fulldateN yymmdd10. ;
run ;

proc print ;
run ;
 
Obs havedateC fulldateC fulldateN
1 2020-05-29 2020-05-29 2020-05-29
2 2020-05 2020-05-01 2020-05-01
3 2020 2020-01-01 2020-01-01

 

ballardw
Super User

Depending on your current variable type:

data junk;
  /* if your date was character*/
  input date $;
  if length(date)=8 then datevar=input(date,yymmdd10.);
  else if length(date)=6 then datevar=input(date,yymmn6.);
  format datevar mmddyy10.;

datalines;
20200305
202004
;

data junk2;
  /* if your date was numeric*/
  input date ;
  if length(put(date,best8. -L))=8 then datevar=input(put(date,best8. -L),yymmdd10.);
  else if length(put(date,best8. -L))=6 then datevar=input(put(date,best8. -L),yymmn6.);
  format datevar mmddyy10.;

datalines;
20200305
202004
;

The YYMMN informat assumes the value is only year and month and treats it as the first day of the month.

SAS Innovate 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 738 views
  • 1 like
  • 3 in conversation