google apps script to reset the graph view to start of the month each month

I don’t like when graphs start showung multiple months of data. And it is tiring to do it manually for each goal. So this Google Apps Script change the graph view to start the first day of the current month. I’ve set it up to execute the 7th of each month.
Changing from UrlFetchApp.fetch to the fetch API it is also usable in any other environment.

const username = '';
const auth_token = '';

function setMonthlyView() {
  const date = new Date()
  const year = date.getFullYear();
  let month = (date.getMonth() + 1).toString();
  month = (month.length === 1 ? '0' : '') + month;
  const goals = JSON.parse(UrlFetchApp.fetch(`${auth_token}`, {method: 'get',muteHttpExceptions: true}).getContentText())
  goals.forEach(x => {
    url = `${username}/goals/${x.slug}.json?auth_token=${auth_token}&tmin=${year}-${month}-01`
    UrlFetchApp.fetch(url, {method: 'put'})


me can be used in the set url line like you did in the set goals line.

Thanks for sharing!

I see you are setting tmin (and not also tmax) so I assume you are letting Beeminder handle that part using its algorithms.

1 Like

thanks, iirc I tried but it wasn’t accepting it, I must have done something else wrong at that point

yeah, but it can be also set to have a view of always the whole month, but both using last day of current month or first day of next month require logic that I wasn’t bothered to write (first day of next mont requires to check if month is december so to have also the year increase, last day of current month requires logic to check length of the month)

1 Like

Maybe there would be a similar way to calculate / obtain the beginning and end of the current month,

var startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
var endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);

And then to use Utilities.formatDate to turn the date into the string in the desired format, maybe

Utilities.formatDate(startOfMonth, timeZone, 'yyyy-MM-dd')

(Or maybe const or let in place of var where the computed value will not change and based on what Google App Script supports.)

1 Like

oh, yes, with:

  const today = new Date()
  var endOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
  const tmax = Utilities.formatDate(endOfMonth, "GMT+0200", 'yyyy-MM-dd')

replacing the timeZone with your own.
Then you can add &tmax=${tmax} at the end of the put url to fix also the end of the graph.

1 Like