Dealing with dates turned into a nightmare for me
Upon deploying my code, all I saw were nulls instead of actual dates. Subsequent versions didn't resolve the issue, even after fixing the code.
I had no choice but to terminate the deployment and initiate a fresh one.
Below is an example code snippet for handling dates:
Schema
const created = fields.newDimension()
.setId('created')
.setName('created')
.setName('Created')
.setType(types.YEAR_MONTH_DAY_SECOND)
Data
/**
* @param {Object} responseRow - key-value pair obtained from API
* @param {DataStudioApp.Fields} requestedFields
*
* @returns {ConnectorGetDataRow}
*/
function getFormattedDataRow_(responseRow, requestedFields) {
const types = cc.FieldType;
if (responseRow === undefined) {
throw 'responseRow is undefined';
}
let row = [];
let value = null;
requestedFields.asArray().map((field) => {
value = responseRow[field.getId()];
if (value === null) {
value = '';
}
if (field.getType() === types.YEAR_MONTH_DAY_SECOND) {
value = formatDateToString_(new Date(value));
}
row.push(value);
});
return {
values: row
}
}
helper
/**
* @param {Date} date
*
* @returns {String}
*/
function formatDateToString_(date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
return `${year}${month}${day}${hours}${minutes}${seconds}`;
}