# Time Flies? Time Travels! Adding Days to Dates in R (Like a Pro)

code
rtip
timeseries
Author

Steven P. Sanderson II, MPH

Published

January 31, 2024

# Introduction

Ever wished you could skip ahead a few days for that weekend getaway, or rewind to relive a magical moment? While real-life time travel remains a sci-fi dream, in R, adding days to dates is a breeze! Today, we’ll explore both base R and the powerful `lubridate` and `timetk` packages to master this handy skill.

# Examples

## Example 1: Base R Basics

Let’s start with the classic. Imagine you have a date stored as `my_date <- "2024-01-31"` (yes, today!). To add, say, 5 days, you can simply use `my_date + 5`. Voila! You’ve time-jumped to February 5th, 2024. But wait, this doesn’t handle months or leap years like a pro.

``````# Create a date object
date <- as.Date("2024-01-31")

# Add 5 days to the date
new_date <- date + 5

print(date)``````
``[1] "2024-01-31"``
``print(new_date)``
``[1] "2024-02-05"``
``class(date)``
``[1] "Date"``
``class(new_date)``
``[1] "Date"``

## Example 2: Enter `lubridate`

This superhero package offers functions like `as.Date()` and `days()` that understand the nuances of dates. Let’s revisit our example:

``````library(lubridate)

my_date <- as.Date("2024-01-31") # Convert string to Date object
future_date <- my_date + days(5) # Add 5 days using days()

future_date # "2024-02-05"``````
``[1] "2024-02-05"``

See the magic? `days(5)` tells R to add 5 days specifically. You can even subtract days (imagine reliving that delicious pizza!):

``````pizza_day <- as.Date("2024-01-27") # Date of pizza bliss
relive_pizza <- pizza_day - days(2) # Travel back 2 days

relive_pizza # "2024-01-25"``````
``[1] "2024-01-25"``

## Example 3: Beyond Days: `timetk` Takes the Wheel

Want to add weeks, months, or even years? `timetk` takes things to the next level with functions like `years()`, `wednesdays()`, and more. Check this out:

``````library(timetk)

graduation %+time% "1 hour 34 seconds"``````
``[1] "2025-06-15 01:00:34 UTC"``
``graduation %+time% "3 months"``
``[1] "2025-09-15"``
``graduation %+time% "1 year 3 months 6 days"``
``[1] "2026-09-21"``
``````# Backward (Minus Time)
graduation %-time% "1 hour 34 seconds"``````
``[1] "2025-06-14 22:59:26 UTC"``
``graduation %-time% "3 months"``
``[1] "2025-03-15"``
``graduation %-time% "1 year 3 months 6 days"``
``[1] "2024-03-09"``

Bonus Tip: Don’t forget about formatting! Use `format()` with options like `"%Y-%m-%d"` to display your dates in your preferred format.