Created
January 8, 2020 11:46
-
-
Save MrMeison/85464d0a67474bc5e789b5743c5ed548 to your computer and use it in GitHub Desktop.
Формула для Google Sheets для получения котировок валюты на заданную дату
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var CBR_ENTRYPOINT = "https://www.cbr.ru/scripts/XML_daily.asp"; | |
/** | |
* Получаем курс ЦБ на дату | |
* | |
* @param {string} currency - код валюты | |
* @param {Date} date - день | |
* @return {Number} | |
* @customfunction | |
*/ | |
function CBR(currency, date) { | |
currency = currency || "USD"; | |
date = date || new Date(); | |
var cache = CacheService.getScriptCache(); | |
date.setDate(date.getDate() + 1); | |
var formatedDate = Utilities.formatDate(date, "MSK", "dd/MM/yyyy"); | |
var cacheKey = formatedDate; | |
var xmlStocks; | |
var xmlStocks = cache.get(cacheKey); | |
if (xmlStocks === null) { | |
xmlStocks = UrlFetchApp.fetch(CBR_ENTRYPOINT + '?date_req=' + formatedDate).getContentText(); | |
cache.put(cacheKey, xmlStocks, 21600); | |
} | |
var document = XmlService.parse(xmlStocks); | |
var root = document.getRootElement(); | |
var valuties = root.getChildren('Valute'); | |
var result; | |
for (var i = 0; i < valuties.length; i++) { | |
var currentCurrency = valuties[i].getChild('CharCode').getValue(); | |
if (currentCurrency === currency) { | |
result = valuties[i].getChild('Value').getValue(); | |
} | |
} | |
if (result === null) { | |
throw new Error('нет данных'); | |
} | |
return Number(result.replace(',', '.')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment