Date Manipulation

Accepted Solution Solved
Reply
Contributor
Posts: 47
Accepted Solution

Date Manipulation

Howdy,

I'm new to programming and trying to figure out the best way to do the following:

I have a macro variable "Start_Date" which will be changed by users:

%let Start_Date = '06FEB2013:0:0:0'dt;

I'd like to take the year of the "Start_Date" value and find the first day of the year before.

The desired output using the date above would be '01JAN2012:0:0:0'dt;

Conceptually I loosely know of two routes to take....

Route 1: I could turn my date into a string, grab the "2013" off my string, create a string resembling a date, then turn this string into a date, arriving at the desired first day of the year.

Something like:

Date = 2/06/2013

=String(2/06/2013)

output: 20130206

=Left(20130206,1,4)

output: 2013

=1&"/"&1&"/"&2013

output: 1/1/2013

=Datevalue(1/1/2013)

Output: 1/1/2013 in date format or 1/1/2012 if subtracting one from the current year.

Route 2: use a SAS function for date shift to calculate at the correct date. In searching the forums I've seen intnx and mdy used in what looks like a similar goal.

Would anyone have an efficient route to pursue?

TS


Accepted Solutions
Solution
‎01-07-2015 10:13 AM
Regular Contributor
Posts: 180

Re: Date Manipulation

I agree with you: second method will do the work.

I suggest the following improvement to get the result in datetime format:

%let Start_Date = '06FEB2013:0:0:0'dt;

data _null_;
prevybeg=dhms(intnx('year',datepart(&Start_Date),-1,'b'),0,0,0);
format prevybeg datetime19.;
put prevybeg=;
run;

CTorres

View solution in original post


All Replies
Super Contributor
Posts: 305

Re: Date Manipulation

Hello,

Second method will do it.

%let Start_Date = '06FEB2013:0:0:0'dt;

data _null_;
prevybeg=intnx('year',datepart(&Start_Date),-1,'b');
format prevybeg date9.;
put prevybeg=;
run;

Solution
‎01-07-2015 10:13 AM
Regular Contributor
Posts: 180

Re: Date Manipulation

I agree with you: second method will do the work.

I suggest the following improvement to get the result in datetime format:

%let Start_Date = '06FEB2013:0:0:0'dt;

data _null_;
prevybeg=dhms(intnx('year',datepart(&Start_Date),-1,'b'),0,0,0);
format prevybeg datetime19.;
put prevybeg=;
run;

CTorres

Contributor
Posts: 47

Re: Date Manipulation

Thank you, intnx worked well. Was an excellent example.

Esteemed Advisor
Esteemed Advisor
Posts: 7,232

Re: Date Manipulation

Personally I don't like macro variables, I tend to store any parameters in datasets and then use them from there.  For instance an example.  I have some records and I want to flag records with a dt after the default then you could just left join that dataset onto your working data and use date functions.  Far easier than messing around with character macro variables.

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 209 views
  • 3 likes
  • 4 in conversation