DT decimal time to clock time conversion

208 Views Asked by At

I'm using DT in shiny to display decimal time currently.

Example here:

library(shiny)
library(DT)
library(dplyr)
library(magrittr)

  # server-side processing

  base<-as.POSIXct('2000-01-01 00:00:00 EST')

  mtcars2 = mtcars[, 5:6]
  mtcars2 %<>% 
    mutate(drat = base+(3600*drat),
           wt = base+(3600*wt))

    DT::datatable(mtcars2,
        extensions = 'Buttons',
        options = list(
          scrollX = TRUE,
          scrollY = TRUE,
          pageLength = 10,
          dom = 'Blfrtip',
          buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
        )
  ) %>% 
  formatDate( 1:2,method = 'toLocaleString', params = list('en-US',year = NULL))

I've been looking into using toTimeString or similar methods from the formatDate() section of DT's functions. How can I go about converting this from decimal time "2.3" hrs into "2:18"? I did find this question after which I have upgraded DT to the latest dev version and included params= but have been unsuccessful in finding the necessary combination to select for just HH:MM.

1

There are 1 best solutions below

1
On BEST ANSWER

I don't think you can achieve it via formatDate(), because I don't see any date conversion method in JavaScript that supports the suppression of any time components. For example, if you read the documentation of toLocalString, you can see that the only possible values for the year component are numeric and 2-digit, and you cannot set it to null to suppress it.

The most straightforward way to display your date/time data in the HH:MM format is to format the data properly before passing it to DT::datatable(), e.g., using the R function format(..., '%H:%M').

I think it is possible to achieve your goal by providing a row or column callback function in JavaScript, but it will be a little bit complicated.