JS dropdown 14 days in future [duplicate] - javascript

This question already has answers here:
How to get next seven days from X and format in JS
(6 answers)
next 7 days in drop-down list [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to create a dropdown list that shows 14 days in the future via JS.
Right now it is showing only 7 days but with duplicates.
What is wrong?
screenshot dropdown
function createDates() {
$("#DT").find('option').remove().end().append('<option value="" selected>~#SELECT_DT~</option>');
var counter = 0;
var index = 1;
console.log(holidays);
while (counter < 14) {
var date = new Date();
date.setDate(date.getDate() + index);
var day = date.getDay();
var month = date.getMonth() + 1;
var isWeekend = (day == 6) || (day == 0);
var checkTime1 = getTimeOfDate(date.getFullYear(), month, date.getDate());
var isFound = false;
var selected = "";
if (index == ~(IF(#DT<>'',#DT,0))~) {
selected = 'selected="selected"';
}
if (!isWeekend) {
if (holidays.length > 0) {
$.each(holidays, function(key, obj) {
var hDay = new Date(obj.DT);
var checkTime2 = getTimeOfDate(hDay.getFullYear(), hDay.getMonth() + 1, hDay.getDate());
if (checkTime1 == checkTime2) {
isFound = true;
}
});
} else {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
if (!isFound) {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
}
index++;
}
}

The second if block should come under the first, also set isFound to false in the beginning:
if (!isWeekend) {
isFound = false;
if (holidays.length > 0) {
$.each(holidays, function(key, obj) {
var hDay = new Date(obj.DT);
var checkTime2 = getTimeOfDate(hDay.getFullYear(), hDay.getMonth() + 1, hDay.getDate());
if (checkTime1 == checkTime2) {
isFound = true;
}
});
if (!isFound) {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
} else {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
}

Related

How to store data correctly to Firebase Realtime Database

I am creating a google add-on that extracts info from the form. I was able to grab the data and store it in a JSON object. However, when I upload the results to Firebase Realtime Database, it stores weirdly (refer to the screenshot below).
The following is how I would like to upload the data to Firebase:
The following is the code where I create the JSON object. Any help would be appreciated.
function makeJSON(form_title, ques_type, form_question, number_of_choices, multi_options, multi_answer, checkBox_options, checkBox_answer, number_of_questions) {
let type_of_question = ques_type.split("~ ");
let questions = form_question.split("~ ");
let mult_options = multi_options.split("~ ");
let mult_answer = multi_answer.split("~ ");
let check_options = checkBox_options.split("~ ");
let check_answer = checkBox_answer.split("~ ");
let multi_answer_list = [];
let checkbox_answer_list = [];
var newDate = new Date();
var dateAdded = newDate.toLocaleString("en-US");
let jsonObj = "{";
//stores and formats forms data in json object
for(var i = 0; i < number_of_questions; i++){
if(i < number_of_questions){
var count = number_of_choices[i]
jsonObj += '"' + [i+1] + '"' + ":{" + '"question-type"' + ":" + '"' + type_of_question[i] + '",' + '"question"' + ":" + '"' + questions[i] + '",';
for (var k = 0; k < count; k++) {
if(type_of_question[i] === "Multiple Choice"){
jsonObj += '"' + "option" + [k+1] + '"' + ":" + '"' + mult_options[k] + '"' + ",";
}
if(type_of_question[i] === "CheckBox"){
jsonObj += '"' + "option" + [k+1] + '"' + ":" + '"' + check_options[k] + '"' + ",";
}
}
for (var j = 0; j < count; j++) {
if(type_of_question[i] === "Multiple Choice"){
if(mult_answer[j].trim().toLowerCase() === 'true'){
multi_answer_list.push(mult_options[j]);
//jsonObj += '"' + "answer" + [j+1] + '"' + ":" + '"' + mult_options[j] + '"' + ",";
}
}
if(type_of_question[i] === "CheckBox"){
if(check_answer[j].trim().toLowerCase() === 'true'){
checkbox_answer_list.push(check_options[j]);
//jsonObj += '"' + "answer" + [j+1] + '"' + ":" + '"' + check_options[j] + '"' + ",";
}
}
}
if(i < number_of_questions){
if(type_of_question[i] === "Multiple Choice"){
jsonObj += '"' + "answer" + '"' + ":" + '"' + multi_answer_list.join(",") + '"' + ",";
}
if(type_of_question[i] === "CheckBox"){
jsonObj += '"' + "answer" + '"' + ":" + '"' + checkbox_answer_list.join(",") + '"' + ",";
}
}
if(type_of_question[i] !== "Multiple Choice" && type_of_question[i] !== "CheckBox"){
jsonObj += '"' + "answer" + '"' + ":" + '"false"' + ","; //default value
}
if(i < number_of_questions-1){
jsonObj += '"' + "date added" + '"' + ":" + '"' + dateAdded + '"' + "},"; //default value
} else{
jsonObj += '"' + "date added" + '"' + ":" + '"' + dateAdded + '"' + "}"; //default value
}
}
}
jsonObj += "}";
console.log(jsonObj);
sendExtractedData(form_title, jsonObj)
}
UPDATE: The following is the approach that I decided to go with (using push()). I was not able to get the structure (screenshot above) but this is close to what I am looking for:
function makeJSON(form_title, type_of_question, questions, multi_options, multi_answer, checkBox_options, checkBox_answer, number_of_questions) {
var dateAdded = new Date().toLocaleString("en-US"), quesList;
let multiple_option = [], checkbox_option = [], multiple_answer = [], checkbox_answer = [], constructedJSON = {};
var uniqueQuizID = Utilities.getUuid(), num, x;
/** set list of options and answers **/
for(var k = 0; k < multi_options.length; k++){
multiple_option.push(multi_options[k]);
if(multi_answer[k]){
multiple_answer.push(multi_options[k]);
}
}
for(var j = 0; j < checkBox_options.length; j++){
checkbox_option.push(checkBox_options[j]);
if(checkBox_answer[j]){
checkbox_answer.push(checkBox_options[j]);
}
}
/****/
console.log(uniqueQuizID);
constructedJSON.quiz_title = form_title;
//stores and formats forms data in json object
for(var i = 0; i < number_of_questions; i++){
if(type_of_question[i].trim() === "Multiple Choice"){
quesList = {"item-type":type_of_question[i], "question":questions[i], "question-options":multiple_option, "question-responses":multiple_answer, "question-submitted":dateAdded};
x= i+1;
num = ''+ x;
constructedJSON[num] = quesList;
} else if(type_of_question[i].trim() === "CheckBox"){
quesList = {"item-type":type_of_question[i], "question":questions[i], "question-options":checkbox_option, "question-responses":checkbox_answer, "question-submitted":dateAdded};
x= i+1;
num = ''+ x;
constructedJSON[num] = quesList;
} else{
quesList = {"item-type":type_of_question[i], "question":questions[i], "question-submitted":dateAdded};
x= i+1;
num = ''+ x;
constructedJSON[num] = quesList;
}
}
//console.log(constructedJSON);
sendExtractedData(uniqueQuizID, constructedJSON);
}
This construct in your code:
jsonObj += '"' + [i+1] + '"' + ":{"...
Is just a very convoluted way to construct an array without an element at the 0th index. Firebase will store it as a JSON object with sequential numeric keys, and then coerce it back to an array when you read it.
I recommend:
Either storing it as an actual array with jsonObj[i+1] = '"' + ":{"
Or using keys that are not just numbers: ``jsonObj['key_'+(i+1)] = ...`, to prevent Firebase from coercing it into an array.
And either way I'd strongly recommend to:
Don't use string concatenation to construct a JSON object. At best it is just harder to read, but it's actually really easy to make a mistake in there.
This entire line:
jsonObj += '"' + [i+1] + '"' + ":{" + '"question-type"' + ":" + '"' + type_of_question[i] + '",' + '"question"' + ":" + '"' + questions[i] + '",';
Would be much more readable like this:
jsonObj[i] = { question-type: type_of_question[i], question: questions[i] };
Consider not using an array, but use push() for the keys. For more on why, read Best Practices: Arrays in Firebase.

repeat the function if element not found

I'm trying to make a script that will notify you if someone gets inline on Whatsapp web and I have this script:
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
// I want it to repeat onlineCheck() after 1 second
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + "Notification sent");
}
}
}
and I want to replace // I don't know what to put here with something that will run the function onlineCheck()
how should I do that
I first had this script:
var onlineCheck1 = window.setInterval(function(){
var x = document.querySelector('[title="online"]');
var name = $('#main>header>div.chat-body>div.chat-main>.chat-title>span').text()
var d = new Date();
if (x == null) {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "offline");
} else {
if (x.innerText === "online") {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "////online///");
} else {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "offline");
}
} ,1000);
but I want it to not do any thing with console log I just want it to repeat itself till it finds the element with the title="online"
Note: I'm using chrome's console to run the script and you can try it yourself if you want.
Invoke the function itself. This is called Recursion. You must be careful to prevent onlineCheck()calls itself infinitely
function onlineCheck()
{
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null)
{
onlineCheck();
}
else
{
if (y.innerText === 'online')
{
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
You can simply call the function as below
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
onlineCheck();
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
You need recursion technique.
While using this technique, the recursive function should need a termination condition to end the process (otherwise the process will infinitely iterates which will eventually cause Maximum call stack size exceeded error)
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
// Be sure to add a termination condition
onlineCheck()
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
As others have pointed out, you could just call the function directly: onlineCheck();. However, the loop condition (document.querySelector('[title="online"]') != null) won't have changed if you do that, so it'll go into an infinite loop/recursion.
Here's another way:
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
setTimeout(onlineCheck, 10);
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
This re-schedules onlineCheck to be called after 10 milliseconds, giving the page a chance to update before checking again. You may want to increase this number to, say, 1000; this way it'll check once every second instead of spinning in place, going "are we done yet? how about now? how about now? and now? now? now?".

Yahoo finance xchange - taking the last update time

I'm doing a query on Yahoo finance xchange, but seems the time of update is not the most updated. Seems random, for each refresh, this value change, sometimes most updated, and sometimes less updated.
There is a way to always get the last time it was updated ?
Thank you.
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDUSD%22%2C%22USDEUR%22%2C%20%22USDJPY%22%2C%20%22USDCNY%22%2C%20%22USDGBP%22%2C%20%22USDBRL%22%2C%20%22EUREUR%22%20%2C%22EURUSD%22%2C%20%22EURJPY%22%2C%20%22EURCNY%22%2C%20%22EURGBP%22%2C%20%22EURBRL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=", function (data) {
var indices = '<p style=\"border:1px solid #ccc; width:auto; padding:0 10px; background:#ddd;\"><strong>' + data.query.results.rate[0].Name + '</strong> ' + money(data.query.results.rate[0].Rate) + '</p>' +
'<p><strong>' + data.query.results.rate[1].Name + '</strong> (Fechamento ' + money(data.query.results.rate[1].Rate) + ') - ' + data.query.results.rate[1].Date + ' - ' + data.query.results.rate[1].Time + '</p>' +
'<p><strong>' + data.query.results.rate[2].Name + '</strong> (Fechamento ' + money(data.query.results.rate[2].Rate) + ') - ' + data.query.results.rate[2].Date + ' - ' + data.query.results.rate[2].Time + '</p>' +
'<p><strong>' + data.query.results.rate[3].Name + '</strong> (Fechamento ' + money(data.query.results.rate[3].Rate) + ') - ' + data.query.results.rate[3].Date + ' - ' + data.query.results.rate[3].Time + '</p>' +
'<p><strong>' + data.query.results.rate[4].Name + '</strong> (Fechamento ' + money(data.query.results.rate[4].Rate) + ') - ' + data.query.results.rate[4].Date + ' - ' + data.query.results.rate[4].Time + '</p>' +
'<p><strong>' + data.query.results.rate[5].Name + '</strong> (Fechamento ' + money(data.query.results.rate[5].Rate) + ') - ' + data.query.results.rate[5].Date + ' - ' + data.query.results.rate[5].Time + '</p>' +
'<p style=\"border:1px solid #ccc; width:auto; margin:20px 0 0; padding:0 10px; background:#ddd;\"><strong>' + data.query.results.rate[6].Name + '</strong> ' + money(data.query.results.rate[6].Rate) + '</p>' +
'<p><strong>' + data.query.results.rate[8].Name + '</strong> (Fechamento ' + money(data.query.results.rate[8].Rate) + ') - ' + data.query.results.rate[8].Date + ' - ' + data.query.results.rate[8].Time + '</p>' +
'<p><strong>' + data.query.results.rate[7].Name + '</strong> (Fechamento ' + money(data.query.results.rate[7].Rate) + ') - ' + data.query.results.rate[7].Date + ' - ' + data.query.results.rate[7].Time + '</p>' +
'<p><strong>' + data.query.results.rate[9].Name + '</strong> (Fechamento ' + money(data.query.results.rate[9].Rate) + ') - ' + data.query.results.rate[9].Date + ' - ' + data.query.results.rate[9].Time + '</p>' +
'<p><strong>' + data.query.results.rate[10].Name + '</strong> (Fechamento ' + money(data.query.results.rate[10].Rate) + ') - ' + data.query.results.rate[10].Date + ' - ' + data.query.results.rate[10].Time + '</p>' +
'<p><strong>' + data.query.results.rate[11].Name + '</strong> (Fechamento ' + money(data.query.results.rate[11].Rate) + ') - ' + data.query.results.rate[11].Date + ' - ' + data.query.results.rate[11].Time + '</p>';
$('#info').html(indices);
});
money = function (n) {
var
c = 4,
d = ',',
t = '.',
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
Well, I ended up constructing a date for each element in the array (map) and then filtering them to the oldest date (reduce)
what do you want to do with this date, I am not sure but here it is...
UPDATED
updated to return full JSON record containing the latest date/time stamp (instead of returning only the latest date)
// sample response
var response = {"query":{"count":12,"created":"2016-04-29T20:13:39Z","lang":"en-us","results":{"rate":[{"id":"USDUSD","Name":"USD/USD","Rate":"1.0000","Date":"N/A","Time":"N/A","Ask":"1.0000","Bid":"1.0000"},
{"id":"USDEUR","Name":"USD/EUR","Rate":"0.8775","Date":"4/29/2016", "Time":"12:38pm","Ask":"0.8777","Bid":"0.8775"},{"id":"USDJPY","Name":"USD/JPY","Rate":"107.3910","Date":"4/29/2016","Time": "2:55pm","Ask":"107.3940","Bid":"107.3910"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.4868","Date":"4/29/2016","Time":"12:49pm","Ask":"6.4878","Bid":"6.4868"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6843","Date":"4/29/2016","Time":"1:15pm","Ask":"0.6844","Bid":"0.6843"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.4492","Date":"4/29/2016","Time":"3:33pm","Ask":"3.4496","Bid":"3.4492"},{"id":"EUREUR","Name":"EUR/EUR","Rate":"1.0000","Date":"1/29/2016","Time":"8:26am","Ask":"1.0002","Bid":"0.9998"},{"id":"EURUSD","Name":"EUR/USD","Rate":"1.1443","Date":"4/29/2016","Time":"3:08pm","Ask":"1.1443","Bid":"1.1443"},{"id":"EURJPY","Name":"EUR/JPY","Rate":"122.5650","Date":"4/29/2016","Time":"4:00pm","Ask":"122.6200","Bid":"122.5100"},{"id":"EURCNY","Name":"EUR/CNY","Rate":"7.4054","Date":"4/29/2016","Time":"2:08pm","Ask":"7.4070","Bid":"7.4037"},{"id":"EURGBP","Name":"EUR/GBP","Rate":"0.7836","Date":"4/29/2016","Time":"3:22pm","Ask":"0.7837","Bid":"0.7836"},{"id":"EURBRL","Name":"EUR/BRL","Rate":"3.9637","Date":"4/29/2016","Time":"4:28pm","Ask":"3.9679","Bid":"3.9595"}]}}};
//console.log(response.query.results.rate);
var times = response.query.results.rate.map(function(elem){
if( elem.Time === 'N/A' || elem.Time === 0){
elem.fullDateTimeStamp = elem.Time;
//console.log(elem);
return elem;
}
// create full date from the time (using time and date combined)
// 1) is it AM or PM
var elemIsPm = (elem.Time.substring(elem.Time.length-2).indexOf("am") == -1);
// 2) remove AM/PM and get hour:min into array
var elemArr = elem.Time.substring(0, elem.Time.length-2).split(":");
// 3) add 12 hours if PM and not noon
if( elemIsPm && elemArr[0] != 12){
elemArr[0] = parseInt(elemArr[0]) + 12;
}
//console.log(elemArr[0]);
// 4) however, if it is 12, we deduct 12 if it's not PM
if( elemArr[0] == 12 && !elemIsPm ){
elemArr[0] = elemArr[0] - 12;
}
// 5) create date object
var elemDateString = elem.Date;
var elemDateOnly = new Date(elemDateString);
//console.log(elemDateOnly);
var elemTS = new Date(elemDateOnly.getFullYear(), elemDateOnly.getMonth(), elemDateOnly.getDate(), elemArr[0], elemArr[1], 0, 0);
elem.fullDateTimeStamp = elemTS;
// console.log(elem);
// 4) return
return elem;
});
console.log( times );
var lastOne = times.reduce(function(prevVal, elem) {
// console.log('p');
// console.log(prevVal );
// console.log('e');
// console.log(elem );
if( prevVal === 'N/A' || prevVal === 0 || prevVal.Time){
return elem;
}
//console.log(prevVal.fullDateTimeStamp);
return (prevVal.fullDateTimeStamp < elem.fullDateTimeStamp)? elem : prevVal;
}, 0);
document.getElementById('latest').innerHTML = JSON.stringify(lastOne);
console.log('====> ');
console.log( JSON.stringify(lastOne.fullDateTimeStamp) );
Last date:
<div id='latest'></div>

jquery ".append" issue in a select box

I have a select option box in html.
<select name="selectDay" id="selectDay" data-mini="true" style="float: left;"></select>
After I append some options with jQuery .append method, those options do not appear.
function showbroadcastsDropDown() {
for (i = 0; i < dateArray.length; i ++ ) {
// variables
var month = dateArray[i].getMonth() + 1;
var year = dateArray[i].getYear();
year += 1900;
//dateArray[i].getDate() + "-" + month + "-" + year
if (i == 0) {
console.log("0");
$("#sendungen select[name='selectDay']").append('<option value="today"' + (actuallyDate == dateArray[i].getDate() ? ' selected=true' : '') + '>today</option>');
} else if (i == 1) {
console.log("1");
$("#sendungen select[name='selectDay']").append('<option value="tomorrow">tomorrow</option>');
} else {
console.log("else");
$("#sendungen select[name='selectDay']").append('<option value="">asdasdasd</option>');
}
console.log(dateArray[i].getDate() + "-" + month + "-" + year);
}
$("#sendungen select[name='selectDay']").selectmenu("refresh");
don't ask about the dateArrayvar.
Thanks in advance!
try:
$("#selectDay").
.append($("<option></option>")
.attr("value",key)
.text(value));
try
$("#sendungen select[name='selectDay']").selectmenu("refresh", true); // force rebuild
Try Below Code:
<select name="selectDay" id="selectDay" data-mini="true" style="float: left;"></select>
<input type="button" id="btnClick" />
Jquery
$(document).ready(function(){
$("#btnClick").click(function(){
$("#selectDay").append(new Option("option text", "value"));
});
});
finally :)
for (i = 0; i < dateArray.length; i ++ ) {
var month = dateArray[i].getMonth() + 1;
if (month == 13) month = 1;
var year = dateArray[i].getYear();
year += 1900;
if (i == 0) {
$("#" + site + " select[name='selectDay']").append("<option value=\"" + dateArray[i].getDate() + "-" + month + "-" + year + "\" " + (actuallyDate == dateArray[i] ? "selected='true'" : "") + ">" + showbroadcastsDropDown_localize.today + "</option>");
} else if (i == 1) {
$("#" + site + " select[name='selectDay']").append("<option value=\"" + dateArray[i].getDate() + "-" + month + "-" + year + "\" " + (actuallyDate == dateArray[i] ? "selected='true'" : "") + ">" + showbroadcastsDropDown_localize.tomorrow + "</option>");
} else {
$("#" + site + " select[name='selectDay']").append("<option value=\"" + dateArray[i].getDate() + "-" + month + "-" + year + "\" " + (actuallyDate == dateArray[i] ? "selected='true'" : "") + ">" + dateArray[i].getDate() + "-" + month + "</option>");
}
}
$("#" + site + " select[name='selectDay']").selectmenu("refresh");

Javascript Date Function Not working

Hi I am trying to add 31 days to 'myDate' which is the current date. It is supposed to get the date add 31 days, then the convertDate function is supposed to translate it to something like 'Nov 31, 2012'. But it doesn't work. Does anyone know why?
Here is the primary function...
function process (infoarray) {
var myDate = new Date();
//var final = convertDate(myDate);
var length = infoarray.length;
var final_string;
for (var b = 0; b < length; b++) {
if (b == 0) {
if (infoarray[b][3] == 'After') {
final_string = '<b>' + infoarray[b][3] + ' ' + infoarray[b][1] + '</b><br/>' + infoarray[b][0] + '<br/>';
} else {
final_string = '<b>' + infoarray[b][1] + ' ' + infoarray[b][3] + ' ' + infoarray[b][2] + '</b><br/>' + infoarray[b][0] + '<br/>';
}
} else {
if (infoarray[b][3] == 'After') {
final_string = final_string + '<br/><b>' + infoarray[b][3] + ' ' + convertDate(myDate.setDate(myDate.getDate() + 31)) + '</b><br/>' + infoarray[b][0] + '<br/>';
} else {
final_string = final_string + '<br/><b>' + infoarray[b][1] + ' ' + infoarray[b][3] + ' ' + infoarray[b][2] + '</b><br/>' + infoarray[b][0] + '<br/>';
}
}
}
return final_string;
}
Here is the line i am focused on from the function above...
final_string = final_string + '<br/><b>' + infoarray[b][3] + ' ' + convertDate(myDate.setDate(myDate.getDate() + 31)) + '</b><br/>' + infoarray[b][0] + '<br/>';
Here is the convertDate function...
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = '0' + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct', 'Nov','Dec'];
var currentMonth = months[month];
return (currentMonth + ' ' + day + ', ' + year);
}
myDate.setDate(...) modifies the value of the Date instance, but doesn't return anything.
You need to call setDate first, then pass the variable to your function.
Here.
First calculate then call
DEMO;
var myDate = new Date();
myDate.setDate(myDate.getDate()+31);
final_string = final_string + '<br/><b>' +
infoarray[b][3] + ' ' +
convertDate(myDate) + '</b><br/>' + infoarray[b][0] + '<br/>';
Or add it to the function:
.... convertDate(myDate,31) + ....
With
function convertDate(d,offset) {
if ( offset ) d.setDate(d.getDate()+offset);
var day = d.getDate();
if (day < 10) {
day = '0' + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct', 'Nov','Dec'];
var currentMonth = months[month];
return (currentMonth + ' ' + day + ', ' + year);
}
DEMO
By using setDate, you tell the Date object to set the day number to something between 32 and 62, which doesn't make much sense.
A good way to add 31 days would be to use getTime, which returns the number of mseconds ellapsed since 1st Jan 1970:
myDate.setTime( myDate.getTime()+31*24*60*60*1000 );
//31Days x 24 hours x 60 minutes x 60 seconds x 1000 msecs

Categories

Resources