1. Creating a DateTime Object in Base R

# Convert a character string to a date object using base R
# The date represents May 8, 2020
d <- as.Date("2/19/2025", format = "%m/%d/%Y")

2. Checking the Data Type of the Date Object

# Print the date object to verify if it is in the correct date format
d
## [1] "2025-02-19"

3. Installing and Loading the lubridate Package

# Install lubridate package if not already installed
if (!require(lubridate)) install.packages("lubridate")
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
# Load the lubridate package
library(lubridate)

4. Extracting Year, Month, Week, and Weekday Numbers

# Extract year, month number, week number, and weekday number
d_year <- year(d)
d_month <- month(d)
d_week <- week(d)
d_day <- wday(d)

# Display the extracted values
d_year
## [1] 2025
d_month
## [1] 2
d_week
## [1] 8
d_day
## [1] 4

5. Creating a New Date 25 Days from d

# Create a new date that is 25 days after d
d_25 <- d + 25

# Display the new date
d_25
## [1] "2025-03-16"

6. Calculating and Verifying the Date Difference

# Compute the difference between d_25 and d using difftime
diff_days <- difftime(d_25, d, units = "days")

# Display the difference
diff_days
## Time difference of 25 days