Javascript Calendar needs new function - javascript

First of all, this forum has been outstanding at helping me learn the limited scripting I do understand so thanks to everyone who contributes.
I have been using the following script on my website to generate a dropdown menu of months/years for a form:
<script>
function CreateMonthDropDown(){
var arrMonthName = new Array();
arrMonthName =
["January","February","March","April","May","June","July","August","September","October","November","December"];
var ThisDate = new Date();
var ThisMonth = ThisDate.getMonth();
var ThisYear = ThisDate.getFullYear();
var tmpMonthYear;
var tmpMonthYearName;
document.write(" <option value=\"\">Any Date</option>");
for ( i = 0; i < 36; i++) {
if ( ThisMonth == 12 ) {
ThisMonth = ThisMonth - 12;
ThisYear = ThisYear + 1;
}
if ( (ThisMonth + 1) < 10 ) {
tmpMonthYear = '0' + (ThisMonth + 1) + '*' + ThisYear + '*';
} else {
tmpMonthYear = (ThisMonth + 1) + '*' + ThisYear + '*';
}
tmpMonthYearName = arrMonthName[ThisMonth] + ' ' + ThisYear;
document.write(" <option value=\"" + tmpMonthYear + "\">" + tmpMonthYearName + "</option>");
ThisMonth = ThisMonth + 1;
}
}
</script>
<font size="1">Travel Date:</font><br><select name="srchStartTravDate">
<script>CreateMonthDropDown();</script></select>
This is great for generating month/year and removing outdated options. However, an API search I use has recently changed their values. Here's what I need:
I need the display to remain the same to the user - January 2018, February 2018 etc.
But I need the value passed through on the form in the following format:
Month needs to be reflected in a two digit number 01, 02 etc. with a * on the end
Year needs to be reflected in a four digit number 2018, 2019 etc. with a * at end
All entries need to be appended with &DateRangeType=4
So for example, May 2018 would pass the value of: 05*2018*&DateRangeType=4
I've searched and searched for a script that will do this and can't find it or figure out how to adapt it to make this work. Is it possible? Any advice would be greatly appreciate. Thanks in advance.

Related

How to Add Two Days from Current Date to the Value of a Hidden Input

This is my code and I want to add two days from the current date to the value of a hidden input. If I borrow now, this results in a waiting period of two days. It will be better if I borrow on Friday; Saturdays and Sundays will not count so the waiting period ends on Monday, four days later.
<input type="hidden" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC;" required/>
You can use JavaScript to add 2 days and For Friday(5) add 4 days to skip Saturday And Sunday plus 2 days:
var currentDate = new Date();
//Checking If Current day is Friday
if(currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
//Formatting to dd/mm/yyyy :
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
// Displaying Fromatted Date
document.getElementById("display").innerHTML = someFormattedDate;
<div id="display"></div>
It has been assumed that nothing is Borrowed on Saturday And Sunday.
The code creates an array of objects referring to the days of the week as well as a Date object oDate used to retrieve the current date information. If the day of the week is not Friday, then user is advised to wait till Friday.
The hidden input "due_date" has its value set to two days from the current date unless that day is Friday in which case the due date becomes 4 days later, to skip the weekend and add the usual 2 days to the waiting period. If the hidden input were part of a form, once it is submitted, and the data validated, assuming submission by POST, one could use variable $_POST["due_date"] in an INSERT query to store that value in a database, making sure to use either mysqli_real_escape_string() or PDO and bound parameters.
Note: I altered the HTML so that both the NAME and ID attributes of the hidden input are both set to "due_date".
var d = document;
d.g = d.getElementById;
var arrDaysOfWeek = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6};
var arrWkDayNames = Object.keys( arrDaysOfWeek );
var oDate = new Date();
var currDay = oDate.getDay();
var md = oDate.getDate();
var mm = oDate.getMonth() + 1;
var y = oDate.getFullYear();
var waitPeriod = 2; // default
var daysTillFriday = (currDay == 0)? arrDaysOfWeek["Friday"]
: arrDaysOfWeek["Friday"] - currDay;
if (currDay == arrDaysOfWeek["Saturday"]) {
daysTillFriday = arrWeekDayNames.length + arrDaysOfWeek["Friday"] - currDay;
}
var mess = "";
if (currDay != arrDaysOfWeek["Friday"] ) {
mess = "\nYou should wait to borrow on Friday, i.e. " + daysTillFriday + " days from today.";
}
if( currDay + 2 != arrDaysOfWeek["Friday"] ) {
daysTillFriday = arrDaysOfWeek["Friday"] - currDay - 2;
mess += "\nSo, best not even in two days. Just wait till Friday which will be in " + daysTillFriday + " days from two days from now.";
}
waitPeriod = (currDay == arrDaysOfWeek["Friday"] )
? 4 //skip sat. & sun. plus 2
: 2; // usual wait period
oDate.setDate(md + waitPeriod);
mess += "\nTo proceed know that the happening date is " + oDate;
//USA date style ...
var date_parts = [ mm, md, y ];
mess += "\nToday is " + arrWkDayNames[ currDay ] + ", " + date_parts.join("/");
d.g("display").textContent = mess;
d.g("due_date").value = oDate;
console.log( "Hidden input due date value: " + d.g("due_date").value );
<div id="display"></div>
<input type="hidden" name="due_date" id="due_date" maxlength="10" style="border: 3px double #CCCCCC;" required/>
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 2;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
answer from - How to add number of days to today's date?
You can do it in php
echo date('Y-m-d', strtotime("+2 days"));
Answer From - Add number of days to a date

Contenteditable field onchange event add date

HTML:
<p id="bon_date" class="inline" style="color:#0000ff;" contenteditable="true" onchange="add7day()"> enter date </p>
javascript:
function add7day() {
var str = document.getElementById(#bon_date).value;
var startdate = str.split("/");
var month = parseInt(stardate[0], 10);
var day = parseInt(stardate[1], 10);
var o_month = parseInt(stardate[0], 10);
var o_day = parseInt(stardate[1], 10);
if (month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10 | month == 12) {
if ((day + 7) > 31) {
month = month + 1;
day = day + 7 - 31;
} else {
day = day + 7;
}
document.getElementById(#bon_date).innerHTML = o_month + "/" + o_day + "~" + month + "/" + day;
} else {
if ((day + 7) > 30) {
month = month + 1;
day = day + 7 - 30;
} else {
day = day + 7;
}
document.getElementById(#bon_date).innerHTML = o_month + "/" + o_day + "~" + month + "/" + day;
}
I can get the string from input type field but I can`t get it from contenteditable field.
and when it runs to var month = parseInt(stardate[0],10); I get errors like:
stardate[0] is not define..
I want input a date by manual and gets the date after 7 days.
Any ideas?
Okay, where to begin.
I'm not going to question the use of a contenteditable element instead of an input type="text" or input type="date" element, I'm just going to fix your JavaScript.
Elements with contenteditable are not converted to input elements or textareas, so they do not have a value property, but they do have a textContent because they're otherwise normal HTML nodes which can have text nodes.
Elements with contenteditable also do not emit an onchange or change event when their text content is edited. You could listen for the input event, but that would break your code, because your function would constantly amend the element's contents every time the user pressed a key—making it practically unusable.
The next best thing to the onchange event is the onblur/blur event, so we'll use that. This means when the user focuses off the event, i.e. clicks outside it (or presses the tab key etc) the function will fire.
stardate[0] comes back as undefined because you didn't define a variable called stardate, you defined startdate. Similarly, none of the code works at all without getting the bon_date element, which in this case would be done by fixing your code so document.getElementById() is given a parameter 'bon_date' (not '#bon_date', because document.getElementById does not use CSS selectors).
// Store the element in a variable so we don't have to keep writing this crap out.
var bd = document.getElementById('bon_date');
// Listen for the blur event by adding an event listener in JavaScript.
// You could also use an 'onblur=' attribute on the element in question.
bd.addEventListener('blur', add7day, false);
function add7day() {
// Get the element's text content.
var str = bd.textContent;
// You could just say startdate = bd.textContent.split("/") and leave out out the str variable.
var startdate = str.split("/");
var month = parseInt(startdate[0], 10);
var day = parseInt(startdate[1], 10);
var o_month = parseInt(startdate[0], 10);
var o_day = parseInt(startdate[1], 10);
if (month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10 | month == 12) {
if ((day + 7) > 31) {
month = month + 1;
day = day + 7 - 31;
} else {
day = day + 7;
}
// no need to use innerHTML, just amend the textContent again
bd.textContent = o_month + "/" + o_day + "~" + month + "/" + day;
} else {
if ((day + 7) > 30) {
month = month + 1;
day = day + 7 - 30;
} else {
day = day + 7;
}
bd.textContent = o_month + "/" + o_day + "~" + month + "/" + day;
}
}
<p id="bon_date" class="inline" style="color:#0000ff;" contenteditable="true"> Enter date (MM/DD) </p>
That gets your code working. Sort of. You should think about validating user input to make sure it's a valid date (not the 1000th day of a 50th month) etc. Moment.js is a very handy JavaScript library to use when dealing with dates and times.

How to make this function not return a negative date diffence?

The function is trying to fund the difference between to dates, but I am struggling to not return a negative number if the date is past a certain point. I have tried a few work around like using ABS but it can cause problems in future areas.
var DateCalc = {};
DateCalc.totalDaysLeft = 0;
DateCalc.calculate = function(dateToParse) {
DateCalc.init(dateToParse);
return DateCalc.stringify(DateCalc.years(), DateCalc.months(), DateCalc.days());
};
DateCalc.init = function(dateToParse) {
var date = DateCalc.parseDate(dateToParse);
var today = Date.now();
var oneDay = 24 * 60 * 60 * 1000;
DateCalc.totalDaysLeft = Math.floor((date - today) / oneDay);
};
DateCalc.parseDate = function(dateToParse) {
var dateVars = dateToParse.split(',').map(Number);
return new Date(dateVars[0], dateVars[1] - 1, dateVars[2]);
};
DateCalc.years = function() {
var years = Math.floor(DateCalc.totalDaysLeft / 365);
DateCalc.totalDaysLeft -= Math.floor(years * 365);
return years;
};
DateCalc.months = function() {
var months = Math.floor(DateCalc.totalDaysLeft / 30);
DateCalc.totalDaysLeft -= Math.floor(months * 30);
return months;
};
DateCalc.days = function() {
return Math.floor(DateCalc.totalDaysLeft / 24);
};
DateCalc.stringify = function(years, months, days) {
var dateString = "";
if (years !== 0)
dateString += years + " years, ";
if (months !== 0)
dateString += months + " months, ";
dateString += days + " day(s).";
return dateString;
};
//here is the .abs() code.
function age(year, month, day) {
var yearDifference = Math.abs(new Date().getFullYear() - year);
var monthDifference = Math.abs(new Date().getMonth() - month + 1);
var dayDifference = Math.abs(new Date().getDate() - day);
var differences = {
year: yearDifference,
month: monthDifference,
day: dayDifference
};
var final = [];
for (var time in differences) {
if (differences[time] > 0) {
var addString = differences[time] + " " + time;
if (differences[time] > 1) {
addString += "s"
}
final.push(addString);
}
}
return final.join(" ");
};
console.log(age(2017, 11, 17));
console.log(age(2016, 1, 2));
//if you tried to look up how far away next January is while you're in December, it will tell you it is 1 year 11 months from now instead of 1 month. This is because it adds the 11 months instead of subtracting it.I am trying to find a solution, as this function is more conscise but the other is more versatile. The function above, I replaced .floor() with rounds the value down with .abs() hoping it would just use the absolute value of the given operation, however, this was not the case.
The problem is that you are using the .abs() function in an inappropriate way. Most mathematical functions do no obey the distributive rule, and the .abs() function belongs to these. For an easier understanding, let us forget your current problem for a moment and let us examine a simple, reduced example:
Let's say you want to know the absolute value of -10. Obviously, the correct result is +10.
On the other hand, -10 could be written as (-20 + 10). But nevertheless, you can not compute abs(-10) using that knowledge:
abs(-20 + 10) = 10, but
abs(-20) + abs(+10) = 30
Applying that knowledge to your problem, we see that abs(Y years + M months + D days) is generally NOT equal to (abs(Y years) + abs(M months) + abs(D days)).
Regarding this problem, there is the additional oddity that each of the terms of the result has another unit, and that the terms depend on each other (e.g. there can be no term like "13 months", because that would be "1 year plus 1 month"), but I won't go into further detail here.
There is a simple solution:
1) Determine the desired resolution of your result (i.e. should your result be accurate to seconds, attoseconds, days or something else).
2) Convert the two dates into the unit determined in step 1), using a randomly chosen, yet fixed point in time as the common starting point.
3) Now you can subtract the two (converted) dates and use the .abs() function without problems.
4) Convert the result back into human readable form.
How do you do that in practice? Well, steps 1), 3) and 4) are easy, but what about step 2)?
Nearly every OS I know (and thus, nearly every programming language) does the conversion needed in step 2) for you. More often than not, the fixed point in time is 1970-01-01 00:00:00, and the OS / programming language provides routines to convert any date / time to the number of seconds (or some other unit) which have elapsed since this fixed point.
For example, in JavaScript, the myDate.getTime() function returns the number of milliseconds which have passed since 1970-01-01 up to myDate.
So convert both dates to "milliseconds since 1970-01-01" and subtract them. Use the .abs() function on the result. Then you have the desired time span as a value of positive milliseconds. Convert that back to human readable form, i.e. years, months and days (which is no problem, is it?)
A second simple solution (just for avoiding negative results):
I hope that you agree with me that comparing two dates is much easier than computing the difference between them (first compare the year; if the years differ, you have undoubtedly found the "greater" date; if the years are equal, do the same with the months, and so on). Then exchange the two dates if necessary. That way, you always can make sure that you subtract the "smaller" date from the "greater" date and that the result always will be positive.
But please note that even when doing so there will still be negative results in parts of the calculation when actually subtracting the dates, so you would have exactly the same problems when using the .abs() function.
A more complicated solution:
You could do the subtraction yourself as well, but then the .abs() function won't help you much. One of the algorithms I can think of could work like a subtraction which is done by hand (I mean the subtraction of normal numbers you have learned in school):
Begin with the least significant unit (for example the days). Subtract the days; if the result is negative, then add 28, 29, 30 or 31 (depending on the month) and make a carry to the months, otherwise keep the result; then do the same thing with the months, and so on. But as I already wrote in my comment, there are many pitfalls when doing so (leap years, months have different numbers of days, and so on), and the .abs() function will not help you here.
Conclusion:
Personally, I would prefer the first (simple) solution I have given. It is easy, understandable and future-proof.
//initial variables
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1;
var year = today.getFullYear();
var otherDate = new Date();
var day2 = 0;
var month2 = 0;
var year2 = 0;
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
function age(day2, month2, year2) {
dayConv = day2;
monthConv = month2;
yearConv = year2;
newDate = day - dayConv;
newMonth = month - monthConv;
newYear = year - yearConv;
}
function mathDate() {
if (newYear >= 1) {
if (newMonth >= 1) {
if (newDate >= 1) {
console.log(newYear + " years and " + newMonth + " months and " + newDate + " days.");
return newYear + " years and " + newMonth + " months and " + newDate + " days.";
} else if (newDate <= 0) {
console.log(newYear + " years and " + newMonth + " months.");
return newYear + " years and " + newMonth + " months.";
}
} else if (newMonth <= 0) {
console.log(newYear + " years and " + newDate + " days.");
return newYear + " years and " + newDate + " days.";
}
} else if (newYear <= 1) {
if (newMonth >= 1) {
console.log(newMonth + " months and " + newDate + " days.");
return newMonth + " months and " + newDate + " days.";
} else if (newDate <= 0) {
console.log(newMonth + " months.");
return newMonth + " months.";
} else if (newMonth <= 0) {
console.log(newDate + " days.");
return newDate + " days.";
}
}
}
age(13, 4, 2016);
mathDate();
Here is the answer I was able to create.

previous quarters in javascript

Forgive me I tried several searches here and other places in general but cant seem to fix issue I am having at the moment. Can someone please help me figure out?
I am trying to find quarter strings from inputdate in JavaScript. For "01/31/2009" it should give Q1,2013 Q4,2012 etc based on offset given as input parameter. when offset is 0 then current quarter, 1 then previous, 2 then previous 2 quarter etc...
my current code: jsfiddle
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
switch (id) {
...
}
Remaining code is in jsfiddle. As you can see, it fails on second last condition even though everything seems ok. Please help me figure out my mistake. Thank you!
Some of your comparisons are off, and Date tries to compensate for months that don't have as many days when you setMonth. This code should work:
function getQuarterStrings(id) {
var d = new Date("03/31/2009");
d.setDate(1);
d.setMonth(d.getMonth() - id * 3);
var month = d.getMonth() + 1;
var year = d.getFullYear();
var quarter = Math.ceil(month / 3);
return ("Q" + quarter + ", " + year);
}
This works, and is a lot more concise. It also allows you to use any offset instead of a limited set of values:
function getQuarterStrings(date, id) {
// quarter is 0-based here
var quarter = Math.floor(date.getMonth() / 3),
year = date.getFullYear();
quarter -= id;
if(quarter < 0) {
var yearsChanged = Math.ceil(-quarter / 4);
year -= yearsChanged;
// Shift quarter back to a nonnegative number
quarter += 4 * yearsChanged;
}
return "Q" + (quarter + 1) + ", " + year;
}
http://jsfiddle.net/dPmf2/6/
You can also get rid of the switch statement by doing this:
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
if (id !== 0){
d.setMonth(d.getMonth() - 3*id);
}
str = getQuarter(d);
return str;
}

Javascript Date from 20/11/2010 to November 20th, 2010?

I have a string value something like the below values
9/21/2010
9/24/2010
And I want to convert those to
September 21nd, 2010
September 24th, 2010
is there an easy way of doing this? Or do I have to do it the hard way?
PS. This is strictly javascript, please don't post jQuery examples.
Thanks!
It depends on what you mean by "the hard way". One way is to split the date into it's components and convert to date (assuming US m/d/y format) and then format the date object how you want:
function toDate(s) {
var bits = s.split('/');
return new Date(bits[2], bits[0] - 1, bits[1]);
}
function addOrdinal(n) {
var ords = ['th','st','nd','rd'];
var o = ('' + (n%10))
if (n > 10 && n < 14) {
return n + 'th';
} else {
return n + (ords[o] || 'th');
}
}
function formatDate(d) {
var months = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
return months[d.getMonth()] + ' ' + addOrdinal(d.getDate()) + ', ' + d.getFullYear();
}
Another is to just convert the month to its name:
function reFormatDate(s) {
var bits = s.split('/');
var months = [,'January','February','March','April','May','June',
'July','August','September','October','November','December'];
return months[bits[0]] + ' ' + addOrdinal(bits[1]) + ', ' + bits[2];
}
Edit
Added the ordinal to date.
You can create new date by just supplying a string to the Date() constructor.
var date = new Date("9/21/2010");
http://www.w3schools.com/jsref/jsref_obj_date.asp
However, to display the date as a string in a customizable way, you'll need to either do it the hard way or using a library, such as dateJS. Javascript provides a couple of output formats for dates, but none of them is especially customizable.
function niceDate(dateString) {
var m = [,'January','February','March','April','May','June','July',
'August','September','October','November','December'];
var s = ['th','st','nd','rd','th','th','th','th','th','th'];
var d = dateString.split('/');
return(m[d[0]-1] + ' ' + d[1] + s[d[1]>4&&d[1]<20?4:d[1]%10] + ', ' + d[2]);
}

Categories

Resources