google-apps-scriptgoogle-forms

How to set default date to today in google form?


I need to set in a google form response the today date (Not hardcoded) when submited

I'm accesing the form, adding a date question, setting the title and the help text, but nothing more

function myFunction() {
    var myForm = FormApp.openById("MyFormID");
    var formDate = myForm.addDateItem();
    formDate.setTitle('Ciclo');
    formDate.setHelpText('Ciclo de registro');
    //This is doing nothing at all
    //var formDateResponse = formDate.createResponse(new Date());
 }

Im only getting the date question unfilled


Solution

  • A FormResponse has a getTimestamp() function built into it.

    If you are using an onSubmit Trigger you can get it by:

    function onSubmit(e){
      var response = e.response;
      var timestamp = response.getTimestamp(); //Date Object!
    }
    

    It's important to note that if you have an onSubmit Trigger in Google Sheets it does not provide the e.response FormResponse object, but instead a values array, namedValues array, or range object.