I have a column with dates and needed to convert them to Unix timestamp. I've managed by converting dates to strings and doing a bit of juggling but was hoping to get insight into a more "elegant" use of GAS date handling and formating. Below is the function I used to get the job done:
/** FUNCTION to convert date column to Unix timestamp
*
*/
function getUnixTime() {
//Set date range to iterate on.
var sheet = SpreadsheetApp.getActiveSheet();
var dateRange = sheet.getRange(1, 1, sheet.getLastRow(), 1);
//Set date format IMPORTANT values will be picked up as displayed.
dateRange.setNumberFormat('D/M/YYYY');
var dates = dateRange.getDisplayValues();
//Set range that will hold unixTime values.
var unixTime = dateRange.offset(0, 1, sheet.getLastRow(), 1).getValues();
//Check date and (empty) unixTime value ranges.
Logger.log(dates);
Logger.log(unixTime);
//Iterate through date and convert to unixTime values.
for (var i = 0; i < dates.length; i++) {
//Set variables to iterate on.
var cellDate = dates[i][0];
var firstIndexOfSlash = dates[i][0].indexOf('/');
var lastIndexOfSlash = dates[i][0].lastIndexOf('/');
//Set day, month, year holders.
var day = cellDate.slice(0, firstIndexOfSlash);
var month = cellDate.slice(firstIndexOfSlash + 1, lastIndexOfSlash);
var year = cellDate.slice(lastIndexOfSlash + 1);
//Set dates to be compared.
var fromTime = new Date(Number(year),Number(month) - 1,Number(day),9,0,0).getTime();
var unixEpoch = new Date(1970,0,1,0,0,0).getTime();
unixTime[i][0] = ((fromTime - unixEpoch) / 1000).toString();
}
//Check unixTime values are correct.
Logger.log(unixTime);
var unixRange = dateRange.offset(0, 1, sheet.getLastRow(), 1).setValues(unixTime);
}
question from:
https://stackoverflow.com/questions/65842003/proper-way-to-convert-dates-to-unix-timestamp-in-google-apps-script 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…