Fetch today date and add 7 days (for Google Opt-In code)

177 Views Asked by At

I don't know Javascript or PHP and I've tried my best finding an answer online but without the basic knowledge I have no clue how to do this. I am sure there are many people like me who are stuck.

My situation is that I need to insert a delivery date by somehow fetching the current date and adding 7 days to it, then input it to the "YYYY-MM-DD" field in the code below.

The best answer I've found is here but I have no clue how to implement it

This is the full code, please help me figure out how to structure it:

<!-- BEGIN GCR Opt-in Module Code -->
<script src="https://apis.google.com/js/platform.js?onload=renderOptIn"
  async defer>
</script>

<script>
  window.renderOptIn = function() { 
    window.gapi.load('surveyoptin', function() {
      window.gapi.surveyoptin.render(
        {
          // REQUIRED
          "merchant_id":"xxxxxxxxxx",
          "order_id": "{BOOKINGNUMBER}",
          "email": "{EMAIL}",
          "delivery_country": "ISO 3166-2:CA",
          "estimated_delivery_date": "YYYY-MM-DD",

          // OPTIONAL
          "opt_in_style": "CENTER_DIALOG"
        }); 
     });
  }
</script>
<!-- END GCR Opt-in Module Code -->
1

There are 1 best solutions below

1
On

sevenDaysFromNow will get the current date and time, then I will set it to current date and time + 7 days. You can read about setDate / getDate here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate

Then I am using formatDate function to convert it to yyyy-mm-dd. Conversion date format was taken from here Format JavaScript Date to yyyy-mm-dd

This is the result:

<!-- BEGIN GCR Opt-in Module Code -->
<script src="https://apis.google.com/js/platform.js?onload=renderOptIn"
  async defer>
</script>
<script>
var sevenDaysFromNow = new Date().setDate(new Date().getDate() + 7);
function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}
  window.renderOptIn = function() { 
    window.gapi.load('surveyoptin', function() {
      window.gapi.surveyoptin.render(
        {
          // REQUIRED
          "merchant_id":"xxxxxxxxxx",
          "order_id": "{BOOKINGNUMBER}",
          "email": "{EMAIL}",
          "delivery_country": "ISO 3166-2:CA",
          "estimated_delivery_date": formatDate(sevenDaysFromNow),

          // OPTIONAL
          "opt_in_style": "CENTER_DIALOG"
        }); 
     });
  }
</script>
<!-- END GCR Opt-in Module Code -->