Date format in HTML table

Viewed 43

I am having trouble changing the date format in my HTML table. I want it to display as "9/1/22" but I am getting "Thu Sep 01 2022 16:55:58 GMT-0400 (Eastern Daylight Time)"

Here is my code:

function sampleFunction() {
  var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  range = sh.getRange("E1").getValues();
  var data = sh.getRange(range).getValues();
  //var htmltable =[];

  var TABLEFORMAT =
    'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;';
  var htmltable = "<table " + TABLEFORMAT + ' ">';

  for (row = 0; row < data.length; row++) {
    htmltable += "<tr>";

    for (col = 0; col < data[row].length; col++) {
      if (data[row][col] === "" || 0) {
        htmltable += "<td>" + "None" + "</td>";
      } else if (row === 0) {
        htmltable += "<th>" + data[row][col] + "</th>";
      } else {
        htmltable += "<td>" + data[row][col] + "</td>";
      }
    }

    htmltable += "</tr>";
  }

  htmltable += "</table>";
  Logger.log(data);
  Logger.log(htmltable);
  MailApp.sendEmail(Session.getActiveUser().getEmail(), "Daily report", "", {
    htmlBody: htmltable,
  });
}

Any help would be greatly appreciated

1 Answers

You can use the Date object to do that:

var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/4/2022

I don't know in which column your date data (you need to post the data in data object) but lets say the date is in the first column then you can do this:

  var data = [];
  var TABLEFORMAT =
  'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;';  
  var htmltable = "<table " + TABLEFORMAT + ' ">';   
    
  for (var row = 0; row<data.length; row++){
    var formattedDate = new Date(data[row][0]).toLocaleDateString("en-US")
    
    htmltable += '<tr>';
    
    for (var col = 0 ;col<data[row].length; col++){
      if (data[row][col] === "" || 0) {htmltable += '<td>' + 'None' + '</td>';} 
      else {
        if (row === 0)  {
          htmltable += '<th>' + data[row][col] + '</th>';
        }        
        else if (col === 0) { htmltable += '<td>' + formattedDate + '</td>'}    
        else {
          htmltable += '<td>' + data[row][col] + '</td>';
        }
      }
    }
    
    htmltable += '</tr>';
  }  

Note: I created local var data in example to make it compile. You should just use your own variables.

Related