Convert date of format char - 20260310 to 03-10-26

Viewed 60

I know it can somehow be achieved using stringr but wanted to check if there is any easy way? sorry for asking this simple question

6 Answers

%Y and %y represent years with and without century respectively.

x <- "20260310"

format(strptime(x, "%Y%m%d"), "%m-%d-%y")
# [1] "03-10-26"
  1. strptime(x, "%Y%m%d") converts the date string to a standard Date object in R.
  2. format(..., "%m-%d-%y") changes its appearance and the output is always character.

Another possible solution, based on lubridate:

library(lubridate)
library(tidyverse)

"20260310" %>% ydm %>% {str_c(day(.), month(.), str_sub(year(.), 3, 4), sep="-")}

#> [1] "3-10-26"

Try

> gsub("(\\d{4})(\\d{2})(\\d{2})", "\\2-\\3-\\1", "20260310")
[1] "03-10-2026"

Another alternative is chron from {chron} package:

x <- "20260310"
x |> chron(format = "ymd") |> chron(format = "m-d-y")
#[1] 03-10-26

The result has "dates" format.

Variation on the lubridate solution

library(lubridate)
x <- "20260310"
f <- stamp("01-10-22", orders = "%d-%Om-%y")
ymd(x) |> f()

stamp() produces a function, that you can apply repeatedly.

require(lubridate)
require(tidyverse)

"20260310" %>% ydm() %>% 
format("%y-%m-%d")

[1] "03-10-26"

"20260310" %>% format("%y-%m-%d") %>% ydm() %>% class()

[1] "Date"
Related