1

I have this code set to get data from an html form onto a google spreadsheet:

 /**
 * record_data inserts the data received from the html form submission
 * e is the data received from the POST
 */
function record_data(e) {
  Logger.log(JSON.stringify(e)); 
  try {
    var doc     = SpreadsheetApp.getActiveSpreadsheet();
    var sheet   = doc.getSheetByName('responses'); 
    var headers = sheet.getRange(1, 1, 1, 
    sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; 
    var row     = [ new Date() ]; 
    for (var i = 1; i < headers.length; i++) { 
      if(headers[i].length > 0) {
        row.push(e.parameter[headers[i]]); 
      }
    }
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
  }
  catch(error) {
    Logger.log(e);
  }
  finally {
    return;
  }

}

new Date () object returns the date properly but time is 4 hours off.

I would like to know how can i set the new Date () object to -4 hours.

Thanks.

EDIT

I added the next variable:

var date =  new Date();date.setHours(date.getHours() - 4);

var row     = [ date ];

But now it only returns year month and day, no hours minutes and seconds.

EDIT 2

Working solution:

var d = new Date();d.setHours(d.getHours() - 4 );

var row     = [ d ];
  • 6
    Are you taking timezones into account? (What timezone are you in?) – Oliver Charlesworth Jun 14 '17 at 14:23
  • 2
    @OliverCharlesworth GMT +4:00 obviously :P – Jared Smith Jun 14 '17 at 14:29
  • 1
    `new Date()` returns different string representations based on the user's timezone and locale. You definitely don't want to hardcode a specific offset, because that will be wrong for anyone who doesn't live in the same timezone as you do (and later on you'll hit daylight savings time and it'll be wrong for you, too.) – Daniel Beck Jun 14 '17 at 14:51
  • That wont be a problem, data returned from the form onto the spreadsheet is only meant to have GMT +4:00. Other users cant access this. – Agustin Cano Jun 14 '17 at 15:58
  • Don't mess with the hour. Just use `.toUTCString()` instead of `.toString()` for serialisation. – Bergi Jun 14 '17 at 16:09
  • Use [MomentJS](http://momentjs.com/docs/). It will help you manipulate and format dates. – ADreNaLiNe-DJ Jun 15 '17 at 13:01

0 Answers0