I have a JS file that is called in a python-based bokeh app. The JS file produces a download button to get a csv of the data used in the interactive charts made by the app. The data contain dates and integers. How can I get the downloaded csv to include the formatting for the dates?
This is the JS file.
function table_to_csv(source) {
const columns = Object.keys(source.data)
const nrows = source.get_length()
const lines = [columns.join('`').replaceAll(/,/g,' ').replaceAll(/`/g,',')]
for (let i = 0; i < nrows; i++) {
let row = [];
for (let j = 0; j < columns.length; j++) {
const column = columns[j]
const val = source.data[column][i]
if (column == 'Date'){
row.push(val.getDate() +'/'+(val.getMonth()+1)+'/'+val.getFullYear()}
else
row.push(val.toString())
}
lines.push(row.join(','))
}
return lines.join('\n').concat('\n')
}
const filename = 'data/survey_results.csv'
const filetext = table_to_csv(source)
const blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' })
//addresses IE
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename)
} else {
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = filename
link.target = '_blank'
link.style.visibility = 'hidden'
link.dispatchEvent(new MouseEvent('click'))
}
The date format in the csv used for the charts is d/m/y.
It took me a while to work out, but (of course) the answer was straightforward. I changed line 12 to:
row.push(new Date(val).toLocaleDateString("en-US"))
One problem was I had misunderstood where the data was coming from. It was from bokeh CDS, with the dates as standard yyyy-mm-ddT00:00:00.000000000.