Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Last active February 12, 2023 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmajstor/993f964e821aca032ce797d972f01b3c to your computer and use it in GitHub Desktop.
Save zmajstor/993f964e821aca032ce797d972f01b3c to your computer and use it in GitHub Desktop.
USD srednji_tecaj in Google Sheets via HNB API V3
// Custom Functions in Google Sheets:
// https://developers.google.com/apps-script/guides/sheets/functions
//
function usdTecajNaDan(value) {
function formatDatum(value) {
switch (typeof value) {
case "string":
return value;
case "object":
// assuming it's a date object
let date = new Date(value);
// return only date part (without time)
return date.toISOString().substring(0, 10);
default:
throw Error(`invalid value type: ${typeof value}`);
}
}
const datumISO = formatDatum(value);
// check date format which HNB API V3 expect, e.g. 2023-02-12
if (!datumISO.match(/^\d{4}-([0]\d|1[0-2])-([0-2]\d|3[01])$/g)) {
throw Error(`invalid ISO date format: ${datumISO}`);
}
const url = "https://api.hnb.hr/tecajn-eur/v3?valuta=USD&datum-primjene=" + datumISO;
const responseText = UrlFetchApp.fetch(url).getContentText();
// Logger.log(responseText);
return JSON.parse(responseText)[0].srednji_tecaj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment