## convert datetime to numeric value

Solved
Occasional Contributor
Posts: 18

# convert datetime to numeric value

I have a date time field DATETIME20 which I converted to DTYEAR4. I would now like to use the year to give a flag of 0 or 1 if present. So for instance '7/23/2012 00:03:09'dt to 2012 to 2012 is present=1, else 0. Can I not just now use 2012 in the code?

I've used the following code but it doesn't work, thx.

data new;

format date dtyear4;

if date=2012 then flag=1; else flag =0

Accepted Solutions
Solution
‎01-04-2018 01:02 PM
Super User
Posts: 7,944

## Re: convert datetime to numeric value

[ Edited ]

The DTYEAR format is used to print a datetime value as only the year. It does not change the value that is stored.

You can either compare the formatted value to the string value of the year or extract the year from the datetime value as number and compare it the numeric value of the year. So you could calculate your boolean FLAG variable this way.

``````flag = '2012' = put(date,dtyear4.) ;
``````

or this way.

``````format date dtyear4.;
flag = '2012' = vvalue(date) ;``````

or this way.

``flag = 2012 = year(datepart(date)) ;``

All Replies
Super User
Posts: 23,357

## Re: convert datetime to numeric value

No, the underlying value is still a datetime, a FORMAT just controls the appearance of the variable.

You can convert it using DATEPART and YEAR.

``if year(datepart(variable)) = 2012 ...``
Solution
‎01-04-2018 01:02 PM
Super User
Posts: 7,944

## Re: convert datetime to numeric value

[ Edited ]

The DTYEAR format is used to print a datetime value as only the year. It does not change the value that is stored.

You can either compare the formatted value to the string value of the year or extract the year from the datetime value as number and compare it the numeric value of the year. So you could calculate your boolean FLAG variable this way.

``````flag = '2012' = put(date,dtyear4.) ;
``````

or this way.

``````format date dtyear4.;
flag = '2012' = vvalue(date) ;``````

or this way.

``flag = 2012 = year(datepart(date)) ;``

☑ This topic is solved.