Home > database >  Convert date of format char - 20260310 to 03-10-26
Convert date of format char - 20260310 to 03-10-26

Time:04-27

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

CodePudding user response:

%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"

CodePudding user response:

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"

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

require(lubridate)
require(tidyverse)

"20260310" %>% ydm() 

[1] "2026-10-03"

"20260310" %>% ydm() %>% class()

[1] "Date"

CodePudding user response:

Try

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