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.
If the data to and from the server is in a different format from what you want to display see the formatting - client-side example. This example also makes use of the datetime-moment sorting plug-in for DataTables to ensure that it can correctly sort the formatted date / time strings shown in the columns.
Buttons has two different methods that can be used to format the data exported differently from the data that is shown in the table: orthogonal options and formatting functions as shown in this example. They both achieve basically the same thing in different ways: namely modification of the output data.
In Editor's datetime input we use displayFormat to describe the format the end user should see, and wireFormat to tell it that the wire format (i.e. the actual value) is in a different format (typically this will be ISO 8601). if (! d) { In addition to the above code, the following Javascript library files are loaded for use in this example:
The data loaded from the server (and submitted to it on create / edit) is in the format specified by the displayFormat option (this parameter is required so Editor's datetime input type can parse and understand the date).
Hi in these cases do I think the best solution is to add a dummy column with the dates in orginal format and have the dates column being sorted according to the values in the DUMMY column. This is in Datatable quite easily done. Example code below.
seq_dates <- data.frame(dates = as.Date("2017-01-01") + 1:6 * 100)
datatable(seq_dates %>% mutate(DUMMY = dates,dates = format(dates, format = "%b-%Y")),
options = list(
columnDefs = list(
list(targets = 1,orderData = 2),
list(targets = 2, visible = FALSE)
)
))
For what it's worth (and using formatDate
), the best that I can do is as follows:
datatable(seq_dates) %>%
formatDate(
columns = 1,
method = "toLocaleDateString",
params = list(
'en-US',
list(
year = 'numeric',
month = 'numeric')
)
)
And this yields date values like 4/2017
and 10/2017
.
I've tried to find these parameter options (in github and the original datatables documentation) but to no avail. The only example in DT uses the parameters of short
, long
and numeric
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With