using the HolidayAPI for bank holidays - javascript

the Question:
How can I use the API to return a boolean value if the date is a bank holiday?
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
if i was to use this code:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=25 returns {"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=26 returns {"status":200,"holidays":[]}
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day; if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/

If you simply want to return a true value if the selected date is a holiday, or false if it is not, you could use a function like this:
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0]; inside of the if statement.

The holidays object must be called as a child of the returned data object:
Since the holidays object is an array you'll also need to use an index to access an item. Assuming there is at least one item returned, you would get the date like so:
var myDate = data.holidays[0].date;
However you should always check that there's at least one object in the array before getting the first one:
if(data.holidays.length > 0){...}
Incidentally, if all you want to do is check if there's a holiday on any particular day then this if statement is all you'll need, since an array length of more than zero means there's at least one holiday.
Edit
A full answer to your question, you could put this inside the .done() method:
var isAHoliday = false;
if(data.holidays.length > 0){
// There's at least one holiday today!
isAHoliday = true;
}
You don't have to declare a local variable, you'll probably use one that's declared elsewhere but that's up to you.

Related

ManyChat, Zapir and JavaScript; how to send out different messages per the end result

I am trying to create questionnaire (15 questions)in my Messenger with the two possible answers Yes and No. Each answer has value (Yes..3) and (No..1). I create Zap where I calculate number like result. I create Java script code by Zapier like next step and here my knowledge is finished. I code to calculate number and like next step sending the message back with answer like number.
What I want from javascript code by Zapier is to calculate answers and based on the results send the answer to Subscriber who answer the Questionnaire.
The answer message according to the scoring answers should be following:
<26
"messege"
26-35
"messege"
>35
"messege"
Here it is how I made until now (sorry but answers are in Slovene language...not important):
return {
calculatednumber: Number(inputData.q1) + Number(inputData.q2) + Number(inputData.q3) + Number(inputData.q4) + Number(inputData.q5) + Number(inputData.q6) + Number(inputData.q7) + Number(inputData.q8) + Number(inputData.q9) + Number(inputData.q10) + Number(inputData.q11) + Number(inputData.q12) + Number(inputData.q13) + Number(inputData.q14) + Number(inputData.q15)
}
if (calculatednumber ==='<25') {
return []; //"Videti je, da so vaše prehranske navade ustrezne. Za izboljšanje priporočamo jemanje multivitaminskih/mineralnih tablet!"
}
if (calculatednumber ==='26,27,28,29,30,31,32,33,34,35') {
return []; //"Multivitaminski/mineralni dodatek k prehrani bo vašemu telesu pomagal ohraniti esencialna hranila, ki jih potrebuje, skupaj z drugimi označenimi dodatki!"
}
if (calculatednumber ==='>36') {
return []; //"Vnos multivitaminov/mineralov bi vam zagotovo koristil. Z bolj uravnoteženo prehrano in dodatkom multivitaminov/mineralov pa bi potrebovali še vnos drugih vitaminov/mineralov!"
};
Thank you for helping me.
You're on the right track! Some pointers:
You'll only ever call one return function, so you don't want to use it for the variable at the top.
You don't need to nest the variable inside an object; it can just be a number
the calculatedNumber variable will never be equal to "<25" because that's a string with a character in it, so your logic branches don't work.
Try this instead:
let calculatedNumber = Number(inputData.q1) + Number(inputData.q2) // + ...
if (calculatedNumber < 25) {
return {message: 'Small Message'} // it's important to return an object
} else if (calculatedNumber > 36) {
return {message: 'Large Message'}
} else {
// everything inbetween 25 and 36
return {message: 'Medium Message'}
}
Anyway, I'd recommend reading through https://learnxinyminutes.com/docs/javascript/ to get a better handle on some of the syntax fundamentals.

Datetime array to array with dates, get corresponding time afterwards

Specific situation.. I'm having an array filled with datetimes I pull in via an api.
Users should be able to select a date from a datepicker (only showing dates available in the array) and afterwards see the corresponding time.
So what I've done..
The original array is obtained via php, so before starting to populate the datepicker with possible dates I create an extra array with dates only.
Since I maintain the key's it's possible to put these 2 arrays next to eachother.
Array looks as following:
["8-8-2017,07:00", "26-8-2017,07:00"];
So far so good...
After a user picks a date I trigger this to be able to start digging for the time corresponding that date.
Now it's getting messy...
$('#datepick').datepicker().on("input change", function(e) {
$("#uur").text('');
var selecteddate = e.target.value;
var searchArr = datesArray;
var ind = searchArr.indexOf(selecteddate.toString());
var result = datesArray.filter(function(item) {
return typeof item == 'string' && item.indexOf(selecteddate.toString()) > -1;
});
var afterComma = result.toString().substr(result.toString().indexOf(",") + 1);
var final = afterComma.replace(":", "u");
$("#uur").text("De warming up party gaat van start rond " + final);
});
The result is that this only works on the last element of the array.
Because I'm splitting based on the comma's. Now I know the easiest way to work arround this would be to change the , that's seperating date and time in another symbol but still I'm wondering why this couldn't be easier.
You convert whole array to string every time. You should change following code:
var afterComma = result.toString().substr(result.toString().indexOf(",") + 1);
To this;
var afterComma = item.toString().substr(item.toString().indexOf(",") + 1);
Edit:
I also missed the loop above
//for every item in result, afterComma will refer to related minute string
for (var item in result) {
var afterComma = item.toString().substr(item.toString().indexOf(",") + 1);
// Do rest here
}

Read multiple JSON API Pages and parse data

Objective: To collect JSON data from forecast API and then read the JSON precipIntensity property over the number of days specified, this code starts at three. Since this take a number of steps to coherently follow please try to make sense of all the code.
My main issue is trying to name the JSON code pages that return then put them into another context to read the precipIntensity
property.
To outline: The back date gets the UNIX time, then requests an API for each forecast day. Then the APIs are put in an array. The array is put in a for() loop to request each JSON script... (now what to do? I would like to be able to read each or calculate something but I do not know how to ask for the formatted code. I can do the remaining bit).
A sample of JSON can be found at my other related post...
https://stackoverflow.com/questions/29949454/store-json-api-object-data-and-reuse-it (I found that the API server stores the data for me...solved)
EDITED since 5/1/15:
//Get the back dated times and current in UNIX,
//later make a lookup that gives datediff from current date and user's date and adjust index i condition to equal exact days.
var totalPrecipSinceDate;
var threeDayAPITimes = [];
for (var i = 0; i <= 2; i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //https://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime(); //1318023197289 number of ms since epoch
var unixEpoch = Math.round(epoch/1000)
threeDayAPITimes[i] = Math.round(unixEpoch - (86400 * i));
/*
var epoch = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
threeDayAPITimes[i] = Math.round(epoch - (86400 * i));
*/
}
//Plan to convert UNIX dates to display
//List of locations: LATITUDE,LONGITUDE
var locations = ["46.3494,-85.5083"]
var currentAPIKey ="privateAPIKey"; //gets an APIkey from user from forecaster input.
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time;
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
});
});
//Process result in foreach loop
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (this.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ;
});
}
alert(eachPrecipSum );
Your loop should be something like this:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time;
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
});
}

Windows Gadget reading specific information from Excel with Javascript

Hi I am trying to write a Windows Gadget that reads out information from an Excelsheet.
The Excelsheet entails a the dates, formated, of the whole year in column A2:A366 and the following columns are the names of the employes B1:Q1.
The gadget is to display the current day and who is marked absent. For each day a person is absent the cell is marked with an X.
I am not a Javascript programmer. And need help. I think I have the basic setup already, and I hope you can help me find my missings.
Explanation:
With the getToday function I am trying to get the date from the PC and format it to a string which I want to use to find in the Column A, which is set to be an array. The same function ist ment to give me back the right row in which it should look for the Xs. If it finds an X it is supposed to return the name of the column i.e the name of the employee.
function getToday (){
var today;
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
today = d.toString (day + "." + month + "." + year);
}
function refreshData(){
oExcel = new ActiveXObject('Excel.Application');
oWkBooks = oExcel.Workbooks.Open("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
oExcelSheet = oWkBooks.Worksheets();
oExcelSheet.Activate();
oExcel.ActiveWorkbook.RefreshAll();
oExcel.ActiveWorkbook.SaveAs("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
oWkBooks.Close();
location.reload();
}
function fetchData() {
function fetchData() {
$('#msg').html("Loading...");
$('#msg').show();
var oExcel;
var oExcelSheet;
var oWkBooks;
var cols;
oExcel = new ActiveXObject('Excel.Application');
oWkBooks = oExcel.Workbooks.Open("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
}
function findToday(stringArray){
for (var j=0; j<stringArray.length; j++) {
if (stringArray[j].match (var today) return cell;
return -1;
}
function returnAbwesentheit() {
var name = name.arr;
for (i=2;i<x.length;i==23) {
if ("cell"=="x") {
document.write (Name(cell));
else
return null;
}
}
::UPDATE::
I had a flash of inspiration. I think I am making this to difficult for myself. Maybe I could make excel do the finding of the date and who is absent. Then I would only generate the Outcome with Javascript into the Windows Gadget.

Looping over array of objects

I'm working on an asp.net app that is utilizing a lot of jQuery UI controls particularly the datepicker.
In my web service I am making a call to the database and retrieving a list of objects and then passing them back to my javascript where I parse them out into an array containing 1 or more objects that look like this:
I need to include some kind of logic in which I can loop through this array of objects and check to see if a javascript Date falls in between the EndDate and StartDate properties of the object so that I can apply a css style for the DatePicker. First question, is there a way to convert the EndDate/StartDate property from this format to a valid javascript Date?
And if so how can I iterate over the array and apply the logic to see if the date falls inside the range?
Any help is greatly appreciated!
Edit: I noticed the image here is kind of hard to see you can more clearly read the properties here:
image link
As requested here is some example code:
function createDateRangesForCalendar() {
$.ajax({
type: "POST",
url: "../Services/BookingService.asmx/GetCalendarDateRanges",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
dateRanges = $.parseJSON(response.d);
},
error: function (xhr, textStatus, thrownError) {
alert(textStatus);
alert(thrownError);
}
});
}
function markInvalidDates(date) {
var isHoliday = false;
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
isHoliday = checkIsHoliday(date);
if ($.inArray(dmy, invalidDays) == -1) {
for (var i = 0; i < dateRanges.length; i++) {
// if date falls in between start and end date of object[i] return something like: return [true, "holiday", "Holiday Rates Apply - Minimum 14 days"];
// else loop through to the next object and try there
}
if (isHoliday == true) {
return [true, "holiday", "Holiday Rates Apply - Minimum 14 days"];
} else {
return [true, ""];
}
} else {
return [false, "unavailable", "Unavailable"];
}
}
First question, is there a way to convert the EndDate/StartDate property from this format to a valid javascript Date?
The format seems to be this: /Date(MILLISECONDS)/. A valid JS date object can be obtained like this: new Date(s.match(/Date\((\d+)/)[1]).
And if so how can I iterate over the array and apply the logic to see if the date falls inside the range?
var re = /Date\((\d+)/;
for(var i in arr) {
var start = new Date(arr[i].startDate.match(re)[1]),
end = new Date(arr[i].endDate.match(re)[1]);
if(myDate < end && myDate > start)
// do something.
}
The above seems to answer your question, the way I understand it.
StartDate and EndDate seem like valid JSON to me, except for the slashes at end and beginning. Otherwise, a simple eval of the value should produce a JS Date Object on which you can operate.
For your second point, what keeps you from classic looping over the array ? Some code would be much more useful to say more.
Just return your start and end dates as numerics, without the \Date()\ wrappers.
In your loop, create a JavaScript date from your target date, i.e. new Date(1334548800000) then use simple comparisons between your target date and those start and end dates.
While you can loop with $.each(yourArray, function(id,item){ date comparison logic here }); I recommend you look into the Underscore library for a decent set of utilities to manipulate JS objects.

Categories