## Year-variable from a date

Solved
Occasional Contributor
Posts: 15

# Year-variable from a date

I have this data set:

Obs.     Indate

1          1/7/2011

2          3/7/2012

3          5/4/2014

4          1/9/2011

5          8/9/2013

6          1/1/2014

How do I create a new variable (year) which looks like this:

Obs.     Year

1          2011

2          2012

3          2014

4          2011

5          2013

6          2014

Accepted Solutions
Solution
‎04-18-2016 05:58 AM
Super User
Posts: 9,599

## Re: Year-variable from a date

Just to add, if its a character variable, then you might be better off with:

year=scan(datevar,3,"/");

If you input it to date and then take a year, you will need to handle the possiblity of missing or invalida dates.  The scan will take the third piece of text delimited by /.

All Replies
Posts: 1,254

## Re: Year-variable from a date

Hi @Gothardt,

If variable INDATE is numeric, you can define

``Year=year(indate);``

``Year=year(input(indate, mmddyy10.));``

provided that INDATE is in MM/DD/YYYY format. If it's DD/MM/YYYY format, please replace mmddyy10. by ddmmyy10. in the above code.

Solution
‎04-18-2016 05:58 AM
Super User
Posts: 9,599

## Re: Year-variable from a date

Just to add, if its a character variable, then you might be better off with:

year=scan(datevar,3,"/");

If you input it to date and then take a year, you will need to handle the possiblity of missing or invalida dates.  The scan will take the third piece of text delimited by /.

Posts: 1,254

## Re: Year-variable from a date

[ Edited ]

Good point from @RW9. The SCAN technique would also be more robust in case of leading blanks
("    1/7/2011").

Edit: By default, this would result in a character variable YEAR, whereas the approach using the YEAR function yields a numeric variable.

Super User
Posts: 13,574

## Re: Year-variable from a date

And depending on what you are doing, if the value is currently a SAS date value use the Year format to display as needed.

Example:

data example;

x='05APR2016'd;

run;

proc print data=have;

var x;

format x year4.;

run;

🔒 This topic is solved and locked.