Choosing most liked post from facebook group - javascript

Well, here is the json file http://herbalista.hol.es/group.json i am working with JSON.parse(); on Google apps script. I temporarily solve with this code by Choosing the post which have more than 15 likes, but i want to choose the one with more likes independently if have or not more than 15 likes.
function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
var i = null;
for (i = 0; item.length > i; i += 1) {
var pubDate = item[i].created_time;
if (pubDate.match(utime)) { var likesdata = item[i].likes.data; var len = likesdata.length;
if (len > 15) {var popular = item[i].link;}}
}} catch(err) {
var err = "ERROR";
}
}

For this you can Choose a default value for a variable like var maxLikes = 0; and verify against len variable.
The code would be something like this:
function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
var i = null;
var maxLikes = 0;
for (i = 0; item.length > i; i += 1) {
var pubDate = item[i].created_time;
if (pubDate.match(utime)) {
var likesdata = item[i].likes.data;
var len = likesdata.length;
if (len > maxLikes) {
maxLikes = len;
var popular = item[i].link;
}
}
}
} catch(err) {
var err = "ERROR";
}
}
Hope that helps!

Related

google docs apps script function calling very slow

I'm writing a google docs apps script in making a google docs add-on. When the user clicks a button in the sidebar, an apps script function is called named executeSpellChecking. This apps script function makes a remote POST call after getting the document's text.
total time = time that takes from when user clicks the button, until the .withSuccessHandler(, that means until executeSpellChecking returns = 2000 ms
function time = time that takes for the executeSpellChecking call to complete from its start to its end = 1400 ms
t3 = time that takes for the remote POST call to be completed = 800ms
t4 = time that takes for the same remote POST call to complete in a VB.NET app = 200ms
Problems:
Why total time to complete is bigger than total function time by a staggering 600ms, what else happens there? shouldn't they be equal? How can I improve it?
Why t3 is bigger than t4 ? Shouldn't they be equal? Is there something wrong with POST requests when happening from .gs? How can I improve it ?
the code is (sidebar.html):
function runSpellChecking() {
gb_IsSpellcheckingRunning = true;
//gb_isAutoCorrecting = false;
gi_CorrectionCurrWordIndex = -1;
$("#btnStartCorr").attr("disabled", true);
$("#divMistakes").html("");
this.disabled = true;
//$('#error').remove();
var origin = $('input[name=origin]:checked').val();
var dest = $('input[name=dest]:checked').val();
var savePrefs = $('#save-prefs').is(':checked');
//var t1 = new Date().getTime();
console.time("total time");
google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
if (gb_IsSpellCheckingEnabled) {
console.timeEnd("total time");
//var t2 = new Date().getTime();
go_TextAndTranslation = JSON.parse(JSON.stringify(textAndTranslation));
var pagewords = textAndTranslation.pagewords;
var spellchecked = textAndTranslation.spellchecked;
//alert("total time to complete:" + (t2-t1) + "###" + go_TextAndTranslation.time);
//irrelevant code follows below...
}
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.executeSpellChecking(origin, dest, savePrefs);
}
and the called function code is (spellcheck.gs):
function executeSpellChecking(origin, dest, savePrefs) {
//var t1 = new Date().getTime();
console.time("function time");
var body = DocumentApp.getActiveDocument().getBody();
var alltext = body.getText();
var lastchar = alltext.slice(-1);
if (lastchar != " " && lastchar != "\n") {
body.editAsText().insertText(alltext.length, "\n");
alltext = body.getText();
}
var arr_alltext = alltext.split(/[\s\n]/);
var pagewords = new Object;
var pagewordsOrig = new Object;
var pagewordsOrigOffset = new Object;
var offset = 0;
var curWord = "";
var cnt = 0;
for (var i = 0; i < arr_alltext.length; i++) {
curWord = arr_alltext[i];
if (StringHasSimeioStiksis(curWord)) {
curWord = replaceSimeiaStiksis(curWord);
var arr3 = curWord.split(" ");
for (var k = 0; k < arr3.length; k++) {
curWord = arr3[k];
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length;
cnt++;
}
offset++;
} else {
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/\n]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length + 1;
cnt++;
}
}
var respTString = "";
var url = 'https://www.example.org/spellchecker.php';
var data = {
"Text" : JSON.stringify(pagewords),
"idOffset" : "0",
"lexID" : "8",
"userEmail" : "test#example.org"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
//var t11 = new Date().getTime();
console.time("POST time");
var response = UrlFetchApp.fetch(url, options);
console.timeEnd("POST time");
//var t22 = new Date().getTime();
var resp = response.getContentText();
respTString = resp;
var spellchecked = JSON.parse(respTString);
var style = {};
for (var k in pagewords){
if (pagewords.hasOwnProperty(k)) {
if (spellchecked.hasOwnProperty(k)) {
if (spellchecked[k].substr(0, 1) == "1") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#000000";
}
if (spellchecked[k].substr(0, 1) == "0") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#FF0000";
}
if (spellchecked[k].substr(0, 1) == "4") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";
}
if (pagewordsOrigOffset[k] < alltext.length) {
body.editAsText().setAttributes(pagewordsOrigOffset[k], pagewordsOrigOffset[k] + pagewordsOrig[k].length, style);
}
}
}
}
//var t2 = new Date().getTime();
console.timeEnd("function time")
return {
"pagewords" : pagewords,
"pagewordsOrig" : pagewordsOrig,
"pagewordsOrigOffset" : pagewordsOrigOffset,
"spellchecked" : spellchecked
}
}
Thank you in advance for any help.
EDIT: I updated the code to use console.time according to the suggestion, the results are:
total time: 2048.001953125 ms
Jun 21, 2021, 3:01:40 PM Debug POST time: 809ms
Jun 21, 2021, 3:01:41 PM Debug function time: 1408ms
So the problem is not how time is measured. function time is 1400ms, while the time it takes to return is 2000ms, a difference of 600ms and the POST time is a staggering 800ms, instead of 200ms it takes in VB.net to make the exact same POST call.
Use console.time() and console.timeEnd():
https://developers.google.com/apps-script/reference/base/console
I modified the code for you. console.timeEnd() outputs the time duration in the console automatically, so I removed the alert for you that showed the time difference.
You might want the strings that I used as the parameter as some sort of constant variable, so there are no magic strings used twice. I hope this is of use to you.
function runSpellChecking() {
gb_IsSpellcheckingRunning = true;
//gb_isAutoCorrecting = false;
gi_CorrectionCurrWordIndex = -1;
$("#btnStartCorr").attr("disabled", true);
$("#divMistakes").html("");
this.disabled = true;
//$('#error').remove();
var origin = $('input[name=origin]:checked').val();
var dest = $('input[name=dest]:checked').val();
var savePrefs = $('#save-prefs').is(':checked');
console.time("total time");
google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
if (gb_IsSpellCheckingEnabled) {
console.timeEnd("total time");
go_TextAndTranslation = JSON.parse(JSON.stringify(textAndTranslation));
var pagewords = textAndTranslation.pagewords;
var spellchecked = textAndTranslation.spellchecked;
//irrelevant code follows below...
}
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.executeSpellChecking(origin, dest, savePrefs);
}
function executeSpellChecking(origin, dest, savePrefs) {
console.time("function time");
var body = DocumentApp.getActiveDocument().getBody();
var alltext = body.getText();
var lastchar = alltext.slice(-1);
if (lastchar != " " && lastchar != "\n") {
body.editAsText().insertText(alltext.length, "\n");
alltext = body.getText();
}
var arr_alltext = alltext.split(/[\s\n]/);
var pagewords = new Object;
var pagewordsOrig = new Object;
var pagewordsOrigOffset = new Object;
var offset = 0;
var curWord = "";
var cnt = 0;
for (var i = 0; i < arr_alltext.length; i++) {
curWord = arr_alltext[i];
if (StringHasSimeioStiksis(curWord)) {
curWord = replaceSimeiaStiksis(curWord);
var arr3 = curWord.split(" ");
for (var k = 0; k < arr3.length; k++) {
curWord = arr3[k];
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length;
cnt++;
}
offset++;
} else {
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/\n]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length + 1;
cnt++;
}
}
var respTString = "";
var url = 'https://www.example.org/spellchecker.php';
var data = {
"Text" : JSON.stringify(pagewords),
"idOffset" : "0",
"lexID" : "8",
"userEmail" : "test#example.org"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
console.time("POST time");
var response = UrlFetchApp.fetch(url, options);
console.timeEnd("POST time");
var resp = response.getContentText();
respTString = resp;
var spellchecked = JSON.parse(respTString);
var style = {};
for (var k in pagewords){
if (pagewords.hasOwnProperty(k)) {
if (spellchecked.hasOwnProperty(k)) {
if (spellchecked[k].substr(0, 1) == "1") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#000000";
}
if (spellchecked[k].substr(0, 1) == "0") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#FF0000";
}
if (spellchecked[k].substr(0, 1) == "4") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";
}
if (pagewordsOrigOffset[k] < alltext.length) {
body.editAsText().setAttributes(pagewordsOrigOffset[k], pagewordsOrigOffset[k] + pagewordsOrig[k].length, style);
}
}
}
}
console.timeEnd("function time");
return {
"pagewords" : pagewords,
"pagewordsOrig" : pagewordsOrig,
"pagewordsOrigOffset" : pagewordsOrigOffset,
"spellchecked" : spellchecked
}
}

Google sheets - How to get row index of a column, based on the index of edit URL from the same row?

I am coding a room booking system using combination of Google forms and Google calendar.
When there is a new booking order:
An event will be automatically created on the selected calendar.
An edit response URL will also be generated automatically and put in column 10 of the spreadsheet in the same row where the form answer was inserted.
// This is the function to generate the edit URL (which works perfectly).
function getEditUrl(request) {
var formRes = FormApp.openById('XXXXXXXXXXXXXXXXXXXXXXXXXXXX');
var sheetRes = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YYYYYYYYYY');
var data = sheetRes.getDataRange().getValues();
var urlCol = 10;
var responses = formRes.getResponses();
var timestamps = [],
urls = [],
resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(responses[i].getEditResponseUrl());
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0] ? urls[timestamps.indexOf(data[j][0].setMilliseconds(0))] : '']);
}
sheetRes.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
};
However, problem occurs when there are more than 2 orders; as the next order will delete the calendar event from the previous order.
// This is the function to update the calendar event.
function updateCalendar(request) {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var range = sheet.getRange(2, 1, lastRow, 13);
var values = range.getDisplayValues();
var calendar = CalendarApp.getCalendarById('XXXXXXXXXXXXXXXXXXXXXXXX#group.calendar.google.com');
for (var i = 0; i < responses.length; i++) {
getConflicts(request);
if (request.eventConflict == "conflict") {
sheet.getRange(lastRow, 11).setValue("conflict");
break;
} else if (request.eventConflict == "approve") {
var newEvent = calendar.createEvent("booked", request.date, request.endTime);
var newEventId = newEvent.getId().split('#')[0];
sheet.getRange(lastRow, 11).setValue("approve");
sheet.getRange(lastRow, 12).setValue(newEventId);
break;
}
}
for (var j = 1; j < values.length; j++) {
if (values[j][10] == "approve") {
var eventEditId = calendar.getEventSeriesById(values[j][11]);
eventEditId.deleteEventSeries();
sheet.getRange(j + 2, 11).setValue("");
getConflicts(request);
if (request.eventConflict == "approve" && values[j][10].length > 1) {
var newEvent = calendar.createEvent("booked", request.date, request.endTime);
var newEventId = newEvent.getId().split('#')[0];
sheet.getRange(j + 2, 11).setValue("approve");
sheet.getRange(j + 2, 12).setValue(newEventId);
break;
} else {
sheet.getRange(j + 2, 11).setValue("conflict");
break;
}
}
}
};
My questions:
How to make sure that when respondent edits his/her own response, it will always update event from the same column as the edit URL? --> I have separate function that will send edit URL to respondents
When there is more than two submission, the 3rd submission will delete event of the 2nd one. (I am sure the issue is on the updateCalendar() function).
I have been struggling so much for the past few days trying to figure out the best way to come up with best loop method. Any help / response is greatly appreciated.
EDIT:
This is the column description of the sheets (separated with |):
Timestamp
Email Address
name
Check-in date
Check-out date
Room
No. of people
total day
total
edit URL
Event Conflict
Event ID
This is the function to get event conflicts in the calendar:
function getConflicts(request){
var conflicts = request.calendar.getEvents(request.date, request.endTime);
if (conflicts.length > 0) {
request.eventConflict = "conflict";
} else {
request.eventConflict = "approve"
}
};
And this is the main function that will be triggered on formsubmit:
function main(){
var request = new Submission(lastRow);
getEndTime(request);
draftEmail(request);
updateCalendar(request);
};
This is the screenshot of the sheet
Finally I found one way to retrieve the edited row by using e.range method. So basically I created another sheet inside the same spreadsheet. When there is a new submission, it will automatically copy the new submission to the second sheet. And when there is an edited submission, it will go through the copy sheet to find the edited row, and then edit it (as well as the calendar). Credit to Tedinoz
function updateCalendarTwo(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var responsename = "AAAAAAAAAAAAAAA"
var copyname = "BBBBBBBBBBBB";
var responsesheet = ss.getSheetByName(responsename);
var copysheet = ss.getSheetByName(copyname);
var calendar = CalendarApp.getCalendarById('CCCCCCCCCCCCCCCCCCCC');
// columns on copysheet
var checkInCol = 4;
var checkOutCol = 5;
var roomNumCol = 6;
var appCol = 11
var eventIDCol = 12;
var revCol = 14;
var response = e.range;
var rRow = response.getRow()
var rLC = responsesheet.getLastColumn();
var cLC = copysheet.getLastColumn();
var rLR = responsesheet.getLastRow();
var cLR = copysheet.getLastRow();
if (rLR > cLR){
var resprange = responsesheet.getRange(rLR,1,1,rLC);
var respdata = resprange.getValues();
copysheet.appendRow(respdata[0]);
var eventTitle = copysheet.getRange(rRow,roomNumCol).getValue();
var startDate = copysheet.getRange(rRow,checkInCol).getValue();
var endDate = copysheet.getRange(rRow,checkOutCol).getValue().getTime()+ 24 * 60 * 60 * 1000;
var conflicts = calendar.getEvents(new Date(startDate), new Date(endDate));
if (conflicts.length < 1) {
var event = calendar.createAllDayEvent(eventTitle, new Date(startDate), new Date(endDate));
var eventID = event.getId().split('#')[0];
copysheet.getRange(rRow,appCol).setValue("approve");
copysheet.getRange(rRow,eventIDCol).setValue(eventID);
} else {
copysheet.getRange(rRow,appCol).setValue("conflict");
}
} else {
var resprange = responsesheet.getRange(rRow,1,1,9);
var respdata = resprange.getValues();
var copyrespRange = copysheet.getRange(rRow,1,1,9);
copyrespRange.setValues(respdata);
var respAppRange = copysheet.getRange(rRow,appCol);
var respApp = respAppRange.getValue();
if (respApp == 'conflict') {
var eventTitle = copysheet.getRange(rRow,roomNumCol).getValue();
var startDate = copysheet.getRange(rRow,checkInCol).getValue();
var endDate = copysheet.getRange(rRow,checkOutCol).getValue().getTime()+ 24 * 60 * 60 * 1000;
var conflicts = calendar.getEvents(new Date(startDate), new Date(endDate));
if (conflicts.length < 1) {
var editedEvent = calendar.createAllDayEvent(eventTitle, new Date(startDate), new Date(endDate));
var editedEventID = editedEvent.getId().split('#')[0];;
copysheet.getRange(rRow,appCol).setValue("edited");
copysheet.getRange(rRow,eventIDCol).setValue(editedEventID);
} else {
copysheet.getRange(rRow,appCol).setValue("conflict");
};
} else {
var eventEditId = copysheet.getRange(rRow,eventIDCol).getDisplayValue();
var editedEvent = calendar.getEventSeriesById(eventEditId);
editedEvent.deleteEventSeries();
var eventTitle = copysheet.getRange(rRow,roomNumCol).getValue();
var startDate = copysheet.getRange(rRow,checkInCol).getValue();
var endDate = copysheet.getRange(rRow,checkOutCol).getValue().getTime()+ 24 * 60 * 60 * 1000;
var conflicts = calendar.getEvents(new Date(startDate), new Date(endDate));
if (conflicts.length < 1) {
var editedEvent = calendar.createAllDayEvent(eventTitle, new Date(startDate), new Date(endDate));
var editedEventID = editedEvent.getId().split('#')[0];;
copysheet.getRange(rRow,appCol).setValue("edited");
copysheet.getRange(rRow,eventIDCol).setValue(editedEventID);
} else {
copysheet.getRange(rRow,appCol).setValue("conflict");
};
};
var revRange = copysheet.getRange(rRow,revCol);
var revOldValue = revRange.getValue();
if (revOldValue == null || revOldValue == ""){
revOldValue = 0;
}
var revNewValue = revOldValue+1;
revRange.setValue(revNewValue);
}
}

How to create dynamic array for each object datetimepicker

Plugin: eonasdan/Bootstrap 3 Datepicker
Explaination:
I want to write an application that user can select 5 different hours for each day. so i created an array and add each day (without duplicate), for example user select 31/12/2017 and 30/12/2017 , now i want to give they this ability to select only 5 different hour for each day that selected.
Tried Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
dateArray[unqdate] = unqtime
}
}
console.log(dateArray);
});
JSFiddle
(For testing, select a date, then click on save button, then check console)
Goal:
var dateArray = {
"31-12-2017": [{
"time": "14:00"
}, {
"time": "17:15"
}],
"30-12-2017": [{
"time": "13:00"
}, {
"time": "12:15"
}]
}
Problem:
I couldn't figured out how can i add another time to each day. it's my first time i work with array and object like this.
I want to prevent duplicate entry and only five different hour per day.
Somehow I'm in learning.
There is some problem with your JS Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
if(dateArray[unqdate] && dateArray[unqdate].length < limit) {
if(!dateArray[unqdate].find((ele) =>ele.time === unqtime)){
dateArray[unqdate].push({"time": unqtime})
}
} else {
dateArray[unqdate] = [{"time": unqtime}]
}
}
}
console.log(dateArray);
});
Note included logic for time split. You can use split by : and take the first 2 element of array.
I have created JSON response for your requirement.
Result :: JSON.stringify(parentObject)
Code is as below.
$(document).ready(function() {
$('#datetimepicker1').datetimepicker({
stepping: 30,
sideBySide: true,
showTodayButton: true,
format: 'DD-MM-YYYY HH:mm:ss',
});
// my code
var limit = 5;
var i = 0;
var parentObject = new Object();
var parentArray = [];
var dateAndTimeObject;
function isDateSelectedExists(date) {
for (var i = 0; i < parentArray.length; i++) {
var obj = parentArray[i];
if (obj["date"] === date) {
return i;
}
}
return -1;
}
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
var tempIndex = isDateSelectedExists(unqdate);
console.log("tempIndex :: " + tempIndex);
if (tempIndex == -1) {
console.log("date doesn't exists");
dateAndTimeObject = new Object();
dateAndTimeObject["date"] = unqdate;
var timeArray = [];
timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
parentArray.push(dateAndTimeObject);
parentObject["res"] = parentArray;
} else {
console.log("date exists");
dateAndTimeObject = parentArray[tempIndex];
var timeArray = dateAndTimeObject["time"];
if(timeArray.length<5) timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
}
console.log("final res :: " + JSON.stringify(parentObject));
}
});});

Javascript - checkDate

How to use the parameter (yearSlipt) of the first function to the second function for i can make the difference between year entered by user and the current year.
function checkDate(date,anneSplit){
var date = new Array();
for(i = 0; i < 3 ; i++){
date[i] = prompt("entrer un date dd/mm/yyyy : ");
console.log(date[i]);
}
for(var i = 0; i < date.length ; i++)
{
daySplit = parseInt(date[i].split("/")[0]);
monthSplit = parseInt(date[i].split("/")[1]);
yearSplit = parseInt(date[i].split("/")[2]);
}
return (daySplit,monthSplit,yearSplit);
console.log(daySplit,monthSplit,yearSplit);
}
function age(ageToday,yearSplit){
checkDate();
var ageToday = new Array();
var d = new Date();
var year = d.getFullYear();
console.log(year);
ageToday = year - yearSplit;
document.write(ageToday);
}
for multi return values, you could use array or json object.
function checkDate(date, anneSplit) {
var date = new Array();
for (i = 0; i < 3; i++) {
date[i] = prompt("entrer un date dd/mm/yyyy : ");
console.log(date[i]);
}
for (var i = 0; i < date.length; i++) {
daySplit = parseInt(date[i].split("/")[0]);
monthSplit = parseInt(date[i].split("/")[1]);
yearSplit = parseInt(date[i].split("/")[2]);
}
return {
daySplit: daySplit,
monthSplit: monthSplit,
yearSplit: yearSplit
};
}
function age(ageToday, yearSplit) {
var checkResult = checkDate();
console.log(checkResult.yearSplit);
// var ageToday = new Array();
// var d = new Date();
// var year = d.getFullYear();
// ageToday = year - yearSplit;
//document.write(ageToday);
}
age();
the problem : the function return only one date but it was 3 dates entred by user
function checkDate(date) {
var date = new Array();
for (i = 0; i < 3; i++) {
date[i] = prompt("entrer un date dd/mm/yyyy : ");
console.log(date[i]);
}
for (var i = 0; i < date.length; i++) {
daySplit = parseInt(date[i].split("/")[0]);
monthSplit = parseInt(date[i].split("/")[1]);
yearSplit = parseInt(date[i].split("/")[2]);
}
return {
daySplit: daySplit,
monthSplit: monthSplit,
yearSplit: yearSplit
};
}
function age(yearSplit) {
var checkResult = checkDate();
var ageToday = new Array();
var d = new Date();
var year = d.getFullYear();
for(var i = 0; i < 3 ;i++)
{
ageToday[i] = year - checkResult.yearSplit;
console.log(ageToday);
}
}
age();

How do I select dates between two dates with Javascript?

I have found similar threads about this but I cant seem to make their solutions work for my specific issue. I currently have a calendar that will highlight the starting date of an Event. I need to change this to highlight the Start Date through the End Date.
Note: I did not write this code. It seems like whoever wrote this left a lot of junk in here. Please don't judge.
attachTocalendar : function(json, m, y) {
var arr = new Array();
if (json == undefined || !json.month || !json.year) {
return;
}
m = json.month;
y = json.year;
if (json.events == null) {
return;
}
if (json.total == 0) {
return;
}
var edvs = {};
var kds = new Array();
var offset = en4.ynevent.getDateOffset(m, y);
var tds = $$('.ynevent-cal-day');
var selected = new Array(), numberOfEvent = new Array();
for (var i = 0; i < json.total; ++i) {
var evt = json.events[i];
var s1 = evt.starttime.toTimestamp();
var s0 = s1;
var s2 = evt.endtime.toTimestamp();
var ds = new Date(s1);
var de = new Date(s2);
var id = ds.getDateCellId();
index = selected.indexOf(id);
if (index < 0)
{
numberOfEvent[selected.length] = 1;
selected.push(id);
}
else
{
numberOfEvent[index] = numberOfEvent[index] + 1;
}
}
for (var i = 0; i < selected.length; i++) {
var td = $(selected[i]);
if (td != null) {
if (!(td.hasClass("otherMonth"))){
td.set('title', numberOfEvent[i] + ' ' + en4.core.language.translate(numberOfEvent[i] > 1 ? 'events' : 'event'));
td.addClass('selected');
}
}
}
},
Instead of trying to select them all, I recommend you iterate over them instead. So something like this:
function highlightDates(startDate, endDate) {
var curDate = startDate;
var element;
$('.selected').removeClass('selected'); // reset selection
while (curDate <= endDate) {
element = getElementForDate(curDate)
element.addClass('selected');
curDate.setDate(curDate.getDate() + 1); // add one day
}
}
function getElementForDate(someDate) {
return $('#day-' + someDate.getYear() + "-" + someDate.getMonth() + "-" + someDate.getDay());
}

Categories