简体   繁体   中英

Table date column formatting with google apps script html service

I am having problems figuring out basic table formatting. I am hoping someone can see what I have and suggest a way of changing the outcome. My Google spreadsheet has 2 columns 'Number' and 'Date'.

My CodeGS looks like

function doGet() {
  return HtmlService
      .createTemplateFromFile('Index')
      .evaluate();
}

function getData() {
  return SpreadsheetApp
      .openById('1111111111111111111111')
      .getActiveSheet()
      .getDataRange()
      .getValues();

} 

My Index.html

<? var data = getData(); ?>
<!DOCTYPE html>
<html>
<Style>
 body {
    font-family: arial;
  }

  table {
    border: 1px solid #ccc;
    width: 100%;
    margin:0;
    padding:0;
    border-collapse: collapse;
    border-spacing: 0;
  }

  table tr {
    border: 1px solid #ddd;
    padding: 5px;
  }

  table th, table td {
    padding: 10px;
    text-align: left;
  }

  table th {
    text-transform: uppercase;
    font-size: 14px;
    letter-spacing: 1px;
  }
  </Style>
  <head>
  </head>
  <body>
<table>
   <thead>
    <tr>
      <th>Number</th>
      <th>Date</th>
    </tr>
  </thead>     
     <? for (var i = 1; i < data.length; i++) { ?>
        <tr>
          <? for (var j = 0; j < data[i].length; j++) { ?>
            <td><?= data[i][j] ?></td>
          <? } ?>
        </tr>
      <? } ?>

</table>

  </body>
</html>

When executed the Date column shows a value like 'Mon Dec 05 2016 00:00:00 GMT-0600 (CST)'

In the spreadsheet and what I would like to see is something like '12/5/2016'

I am hoping someone can show me how to make this work

Regards,

Chris

This is by no means an elegant solution but to completely control the date format for display I use the following:

var dateStr = 'Mon Dec 05 2016 00:00:00 GMT-0600 (CST)';

function pad(n){
  var pad = "";  
  if(n < 10){pad = "0" + n}else{pad = n};  
  return pad;
}

function shortDate(dateString){

  var d = new Date(dateString);

  var curr_date = d.getDate();
  var curr_month = d.getMonth() + 1;//zero indexed
  var curr_year = d.getFullYear();

  var shortDate = pad(curr_date) + "/" + pad(curr_month) + "/" + curr_year;

  return shortDate;

 }

 console.log(shortDate(dateStr));

This code will output a UK format date, you'll want to switch pad(curr_date) and pad(curr_month).

This does mean that you would have to write a table generating function to replace the way in which your table is generated currently as you need to handle the date values independently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM