Format date in Datatable output

Viewed 7211
library(DT)
seq_dates <- data.frame(dates = as.Date("2017-01-01") + 1:6 * 100)
datatable(seq_dates) %>% formatDate(1, "toDateString")

I get a datatable in viewer pane displaying dates in following format "Mon May 22 2017".

Q - How can I format date column as "MM-YY"

If I do,

dplyr::mutate(seq_dates, dates = format(dates, format = "%b-%Y")) %>%
  datatable()

I get the required date format, but in this second case column sorting doesn't work (sorting is done on alphabets rather than dates.)

P.S - I'm implementing this on shiny.

4 Answers

There is a render method that you can use:

datatable( ...
  options = list(..
     columnDefs = list(..
        list(targets = c(1), render = JS(
                             "function(data, type, row, meta) {",                              
                              "return type === 'display' ? new Date(data).toLocaleString() : data;"))))
                        
Related