rguides

How to Convert Strings to Dates in R with lubridate

To convert strings to dates in R, the lubridate package handles this with functions that auto-detect common formats, while base R’s as.Date() gives precise control. This is essential when working with real-world data where dates arrive as text from CSV files, databases, or APIs. Both approaches return proper Date objects that support arithmetic and formatting.

library(lubridate)

# Auto-detection of common date formats
ymd("2026-03-14")                # [1] "2026-03-14"
mdy("March 14, 2026")            # [1] "2026-03-14"
dmy("14/03/2026")                # [1] "2026-03-14"
ymd_hms("2026-03-14 10:30:00")   # POSIXct with time

# Base R with explicit format string
as.Date("03/14/2026", format = "%m/%d/%Y")
# [1] "2026-03-14"

Common format codes: %Y (4-digit year), %y (2-digit), %m (month), %d (day), %B (full month name), %b (abbreviated). For inconsistent formats in a single column, lubridate::parse_date_time() accepts multiple order specifications: parse_date_time(dates, orders = c("ymd", "mdy", "Bdy")).

# Handle mixed-format dates
dates <- c("2026-03-14", "03/14/2026", "March 14, 2026")
parse_date_time(dates, orders = c("ymd", "mdy", "Bdy"))
# [1] "2026-03-14" "2026-03-14" "2026-03-14"

# Check for parsing failures
result <- as.Date(c("2026-03-14", "not-a-date", "2026-03-15"))
sum(is.na(result))  # [1] 1

Both as.Date() and lubridate functions return NA for strings they cannot parse. readr::parse_date() provides a problems() attribute listing which rows failed and why — useful for diagnosing import issues. For mixed-format columns, combine attempts with dplyr::coalesce(): coalesce(mdy(x), ymd(x)). When dates include time components, ymd_hms() and as.POSIXct() create datetime objects that preserve hours, minutes, and seconds alongside the calendar date. For extracting date parts after conversion, lubridate::year(), month(), and day() pull individual components without string manipulation.

See also