Is there a way to use the format
function on a date object, specifically an object of class POSIXlt
, POSIXct
, or Date
, wi
You can do this with a simple change to your strftime
format string. However, it depends on your platform (Unix or Windows).
Insert a minus sign (-
) before each term you'd like to remove leading zeros from:
format(as.Date("2020-06-02"), "%Y, %-m, %-d")
[1] "2020, 6, 2"
Insert a pound sign (#
) before each desired term:
format(as.Date("2020-06-02"), "%Y, %#m, %#d")
[1] "2020, 6, 2"
A more general solution using gsub, to remove leading zeros from the day or month digits produced by %m or %d. This deletes any zero that is not preceded by a digit:
gsub("(\\D)0", "\\1", format(as.Date("1998-09-02"), "%Y, %m, %d"))
I have discovered a workaround by using year
, month
and day
function of lubridate package. With the help of glue::glue, it is easy to do it as following:
require(lubridate)
require(glue)
dt <- "1998-09-02"
glue("{year(dt)}, {month(dt)}, {day(dt)}")
# 1998, 9, 2
Just remove the leading zeros at the end:
gsub(" 0", " ", format(as.Date("1998-09-02"), "%Y, %m, %d"))
## [1] "1998, 9, 2"
Use %e to obtain a leading space instead of a leading zero.