Google-apps-script – Time until Specified Date

dategoogle-apps-scriptgoogle-slides

Looking to add an auto-updated amount of time countdown timer into Google Slides with the working script from this question.

Getting Setup

  1. Go to Google Slides
  2. Create a text box, right click to find Alt text and input "$date" under Description
  3. Go to Tools>Script Editor
  4. Add the function below
  5. Output should be PST Current Date

Right now, the output is the current date (12/25/2019). I'd like to input a manually specified date (eg December 25th, 2030 or 12/25/2030) to have the resulting output be 11 years, 0 months, 3 days.

function onOpen() {
 var date = Utilities.formatDate(new Date(), "PST", "M/d/yyyy"); 
 var pattern = "\\b\\d{1,2}/\\d{1,2}/\\d{4}\\b"; 
 var slides = SlidesApp.getActivePresentation().getSlides();
 var slidesLength = slides.length;
 for (var i = 0; i < slidesLength; i++) {  
   var shapes = slides[i].getShapes();
   var shapesLength = shapes.length;
   for (var j = 0; j < shapesLength; j++) {
     if (shapes[j].getDescription() == "$date") {
       var textRange = shapes[j].getText();
       textRange.clear();
       textRange.insertText(0, date);
      }
    }
  }
}

Best Answer

In case it's useful, I was able to get the desired output with the below code and updated the output to be in Years, Days and Hours instead. Others can use the pluralized names to get their desired "timedelta" output.

function onOpen() {
  var date = Utilities.formatDate(new Date(), "PST", "M/d/yyyy");
  var hd=new Date('2030-12-25T00:00:00+0000').valueOf();
  var td=new Date().valueOf();
  var sec=1000;
  var min=60*sec;
  var hour=60*min;
  var day=24*hour;
  var year=365*day;
  var diff=hd-td;
  var years = Math.floor(diff/year);
  var days=Math.floor(diff%year/day);
  var hours= Math.floor(diff%day/hour);
  var end_date = years + ' years \n' + days + ' days \n' + hours + ' hours';
  var pattern = "\\b\\d{1,2}/\\d{1,2}/\\d{4}\\b"; 
  var slides = SlidesApp.getActivePresentation().getSlides();
  var slidesLength = slides.length;
  for (var i = 0; i < slidesLength; i++) {  
    var shapes = slides[i].getShapes();
    var shapesLength = shapes.length;
    for (var j = 0; j < shapesLength; j++) {
      if (shapes[j].getDescription() == "$date") {
        var textRange = shapes[j].getText();
        textRange.clear();
        textRange.insertText(0, end_date);
      }
    }
  }
}