Announcement Icon Online training class for Clinical R programming batch starts on Monday, 02Feb2026. Click here for details.

Extract Day, Month, Year, Weekday from Date


Lesson Description
-
  • Sometimes, we want to work with the concept of "Extract Day, Month, Year, Weekday from Date" in a clear, repeatable way.
  • This lesson walks through a simple example and shows the key steps.
  • We will see one approach on how we can do it in SAS and R.


data dates;

    input dob : date9.;

    
format dob date9.;

    
datalines;

01JAN2000 
15FEB1995 
20DEC2010 
;

run;


data extract_parts;

    set dates;
    day = day(dob);
    month = month(dob);
    year = year(dob);
    weekday = weekday(dob);

run;

  • Extracts day, month, year, and weekday components from a date.
  • `weekday()` returns 1 for Sunday through 7 for Saturday.
library(tidyverse)
library(lubridate)

dates <- tribble(
  ~dob,
  "2000-01-01",
  "1995-02-15",
  "2010-12-20"
) %>%
  mutate(dob = ymd(dob)) %>%
  mutate(
    day = day(dob),
    month = month(dob),
    year = year(dob),
    weekday = wday(dob, label = TRUE)
  )
  • `ymd()` parses date strings.
  • `day()`, `month()`, `year()`, and `wday()` extract date parts.
  • `wday(..., label = TRUE)` gives weekday names.
dates <- data.frame(
  dob = c("2000-01-01", "1995-02-15", "2010-12-20")
  , stringsAsFactors = FALSE
)

dates$dob <- as.Date(dates$dob)

dates$day <- as.integer(format(dates$dob, "%d"))

dates$month <- as.integer(format(dates$dob, "%m"))

dates$year <- as.integer(format(dates$dob, "%Y"))

dates$weekday <- weekdays(dates$dob)

print(dates)
  • as.Date() parses strings; format() extracts date parts.
  • weekdays() returns the day name.