SAS: Extract Week, Day, Month and Year from Date

Deepanshu Bhalla Add Comment

This tutorial explains how to extract the week, day, month and year from a date in SAS, along with examples.

Sample SAS Dataset

Let's create a sample SAS dataset that will be used in the examples of this article.

data mydata;
    input date_var date9.;
    format date_var date9.;
    datalines;
01JAN2023
10JAN2023
15JAN2023
20JAN2023
25JAN2023
01FEB2023
10FEB2023
15FEB2023
20FEB2023
25AUG2023
;
run;

How to Calculate Week Number of Year

In SAS, the WEEK function calculates the week number of the year.

data want;
set mydata;
weeknumber = week(date_var); 
run;
Week Number of Year in SAS

How to Calculate Week Number of Month

The following code uses the intck function to calculate the number of weeks between the beginning of the month and the given date. The intnx function is used to find the first day of the month ('B' option stands for 'beginning'). Adding 1 to the result accounts for the week number starting from 1.

data want;
set mydata;
weeknumber = intck('week', intnx('month', date_var, 0, 'B'), date_var) + 1;
run;
Week Number of Month in SAS

How to Extract Month from Date

In SAS, the month function is used to extract month from a date.

data want;
set mydata;
monthnumber = month(date_var);
run;
Extract Month from Date in SAS

How to Extract Day from Date

In SAS, the day function is used to extract day from a date.

data want;
set mydata;
daynumber = day(date_var);
run;

How to Extract Year from Date

In SAS, the year function is used to extract year from a date.

data want;
set mydata;
yearnumber = year(date_var);
run;
Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 0 Response to "SAS: Extract Week, Day, Month and Year from Date"
Next → ← Prev