How to get the value of the month to the database - javascript

I have this function, that gives the user the correct amount of buttons depending on the month. So if the user loads the page, Februari will show up, and 28 buttons aswell. If the user changes to March, there will be 31 buttons. The user is able to click on the button, and the corresponding button will be added to the mySql database. So if the user chooses Februari, and the button 3, the value in the database will say 2018-02-03. The problem is, and what I need help with, is if the user changes the month on the page, it does not change the value in the database. The month value in the database is always the current month of the year. Tried different solutions but nothing works. The value of the month is in a h2 with the id "displayingMonth".
Function:
function drawTable(daysInMonth) {
var cellsToDraw = daysInMonth;
var table = document.getElementById("table");
var dateObj = new Date();
var month = dateObj.getMonth()+1;
var day = dateObj.getDate();
var year = dateObj.getFullYear();
newdate = year + "-" + month;
table.innerHTML = "";
for (r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (c = 0; c < 31 && cellsToDraw > 0; c++) {
v = c +1;
//var newCell = document.createElement("td");
var newCell = document.createElement("input");
newCell.setAttribute("type", "radio");
newCell.setAttribute("name", "day");
newCell.setAttribute("value", newdate + "-" + v);
newRow.appendChild(newCell);
newCell.innerHTML =
cellsToDraw--;
}
}
}
to get the month displayed:
function daysInMonth(month, year) {
var days;
switch (month) {
case 1:
var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
days = leapYear ? 29 : 28;
break;
case 3:
case 5:
case 8:
case 10:
days = 30;
break;
default:
days = 31;
}
return days;
}
To get the month:
window.onload = function() {
var month = new Date();
var index = month.getMonth();
var months = ["Januari", "Februari", "March", "April", "May", "June", "July", "Augusti", "September", "October", "November", "December"];
document.getElementById("todayField").innerHTML = months[month.getMonth()];
// Draws a table for the current month
drawTable(daysInMonth(index, 2018));
}
to get the next month
function next() {
var months = ["Januari", "Februari", "March", "April", "May", "June", "July", "Augusti", "September", "October", "November", "December"];
var weeks = ["Sunday", "Monday", "Tuseday", "Wednesday", "Thursday", "Friday", "Saturday"];
var nextMonth = index + 1 > 11 ? 0 : index + 1;
index = nextMonth;
document.getElementById("displayingMonth").innerHTML = months[nextMonth];
drawTable(daysInMonth(index, 2018));
}
HTML
<input id="newCell"type="hidden"name="day" value="">
All help is appriciated!

Alright, some slight adjustments here. This is highly specific to your code, so bear with the changes. The issue lies with the use of var dateObj = new Date(); and then pulling the month from it to add to each 'day' radio input a user chooses.
Each input is using the 'current date' for that, and thus pulls the wrong month for what its passing.
Instead, you'll need to push the selected month date into the drawTable function, so it can build properly from that. And example of such would be:
function drawTable(daysInMonth,selectedMonth) {
...
// selectedMonth has the proper index for the Date() function
// setting 2018 here, because your code isnt inc years yet
var dateObj = new Date(2018, selectedMonth, 1, 0, 0, 0, 0);
...
}
window.onload = function() {
...
drawTable(daysInMonth(index, 2018), month.getMonth());
}
function next() {
// you may want to deal with looping to the next year here too
...
drawTable(daysInMonth(index, 2018), nextMonth);// nextMonth holds proper index
}
I think I should note that this passes the "month index", because new Date() takes a month index of 0 - 11. So passing it straight from a .getMonth() is the most compatible (no need to add +1 or -1 to them).
Here is also full chunk of your code with many changes applied to reduce some complexity and allow for years to roll as next month loops. There are a lot of changes in here, but mainly, it relies a lot more on the Date() object. No need for the daysInMonth() function you have.
// set as global
var showDate = new Date();
var months = ["Januari", "Februari", "March", "April", "May", "June",
"July", "Augusti", "September", "October", "November", "December"];
var weeks = ["Sunday","Monday","Tuseday","Wednesday","Thursday","Friday","Saturday"];
function drawTable(forDate) {
var daysInMonth = new Date(forDate.getFullYear(),forDate.getMonth()+1,0).getDate();
// ^^^ magic way to get number of days!
var cellsToDraw = daysInMonth;
// for a zero-padded non-index YYYY-MM prefix value:
var newdate = forDate.getFullYear() +"-"+ ("0"+ (forDate.getMonth() + 1)).slice(-2);
var table = document.getElementById("table");
table.innerHTML = "";
for (var r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (var c = 0; c < 31 && cellsToDraw > 0; c++) {
// for a zero-padded day to tack onto newdate
var day = ("0" + (c + 1)).slice(-2);
var newCell = document.createElement("input");
newCell.setAttribute("type", "radio");
newCell.setAttribute("name", "day");
newCell.setAttribute("value", newdate + "-" + day);// makes YYYY-MM-DD
newRow.appendChild(newCell);
newCell.innerHTML = '';
cellsToDraw--;
}
}
}
window.onload = function() {
document.getElementById("todayField").innerHTML = months[showDate.getMonth()];
drawTable( showDate );
};
function next() {
if (showDate.getMonth() == 11) {
showDate.setMonth( 0 );
showDate.setFullYear( showDate.getFullYear()+1 );
} else {
showDate.setMonth( showDate.getMonth()+1 );
}
document.getElementById("displayingMonth").innerHTML = months[showDate.getMonth()];
drawTable( showDate );
}
function prev() {
if (showDate.getMonth() === 0) {
showDate.setMonth( 11 );
showDate.setFullYear( showDate.getFullYear()-1 );
} else {
showDate.setMonth( showDate.getMonth()-1 );
}
document.getElementById("displayingMonth").innerHTML = months[showDate.getMonth()];
drawTable( showDate );
}

Related

Why does my calendar start a day late in december?

I'm supposed to build a calendar with only html, css, and javascript - no php, no jquery, nothing. I have been working on a bug in my code all weekend, but I don't know where it comes from. I don't know what to do. This is my code:
"use strict";
window.onload = init;
function init() {
var day = new Date();
var month = day.getMonth() + 1;
var year = day.getYear() + 1900;
var next = document.getElementById("next");
var previous = document.getElementById("previous");
next.onclick = nextMonth(month);
previous.onclick = previousMonth(month);
generateCalendar(month, year);
}
function generateCalendar(_month, _year) {
var table = document.getElementById("calendar");
var month = ["Januar", "Februar", "März", "April", "Mai", "Juni",
"Juli", "August", "September", "Oktober", "November", "Dezember"];
var day = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];
var totaldays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
//determining the first day of the month
var firstday = new Date(_year, _month + 1, 1);
var start = firstday.getDay() + 1;
var end = totaldays[_month - 1]; //determining the length of the month
//February
if (end === totaldays[1]) {
//leap years (% means modulo)
if ((_year % 4 === 0 && _year % 100 !== 0) || _year % 400 === 0) {
end = 29;
}
}
//tale header
var head = month[_month - 1] + " " + _year;
var caption = table.createCaption();
caption.innerHTML = head;
var cell;
var row = table.insertRow(0);
for (var i = 0; i <= 6; i++) {
cell = row.insertCell(i);
cell.innerHTML = day[i];
}
var days = 1;
for (var i = 0; i <= 5; i++) { //started week in a month
row = table.insertRow(i + 1);
for (var j = 0; j <= 6; j++) { //days of a week
//regular calendar days
if (days <= end && (i > 0 || j >= start)) {
cell = row.insertCell(j);
cell.innerHTML = days;
days++;
} else {
//Days that aren't in the current month are shown as empty
cell = row.insertCell(j);
cell.innerHTML = "";
}
}
}
}
function nextMonth(_month) {
//contruction site
}
function previousMonth(_month) {
//construction site
}
My html file pretty much only has a <table> with the id named above.
So the calendar is in German obviously. As you can see (I hope) I tried to put the first day of the month on a field in an array from 0-6 for my week days which is very basic and it works!
Until December. The first day of December is supposed to be a Friday, but in my calendar it's on a Saturday and I have no idea why it jumps a day ahead. I debugged it and all I see is it skips a day in my array. I suppose it has something to do with the +1 at firstday.getDay() but I need that because all the Date functions are so inconsistent.

Only run function if date is less than the other

I have built a counter that counts (both up and down) the date. I only want to have the counter function run down, and once it hits the current date or later to stop running altogether. Right now it alerts saying the date is reached but continues counting even though it has reached the date.
Here is the JSFiddle for the counter.
Here is the Boolean
if(tDate == eDate) {
alert('Today is the event!');
return false;
// clearTimeout( countDown.prototype.update() );
} else {
counter();
}
Here is the whole code
$(document).ready(function() {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var d = new Date();
var month = monthNames[d.getMonth()];
var day = d.getUTCDate();
var year = d.getUTCFullYear();
var eMonth = $("#d-month").html();
var eDay = $("#d-day").html();
var eYear = $("#d-year").html();
var tDate = month + " " + day + " " + year;
var eDate = eMonth + " " + eDay + " " + eYear;
alert("today's date: " + tDate + " event's date: " + eDate);
if(tDate == eDate) {
alert('Today is the event!');
return false;
// clearTimeout( countDown.prototype.update() );
} else {
counter();
}
function counter() {
function countDown(initDate, id) {
this.counterDate = new Date(initDate);
this.update();
}
countDown.prototype.calculateUnit=function(secDiff, unitSeconds){
var tmp = Math.abs((tmp = secDiff/unitSeconds)) < 1? 0 : tmp;
return Math.abs(tmp < 0 ? Math.ceil(tmp) : Math.floor(tmp));
}
countDown.prototype.calculate=function(){
var secDiff = Math.abs(Math.round(((new Date()) - this.counterDate)/1000));
this.days = this.calculateUnit(secDiff,86400);
this.hours = this.calculateUnit((secDiff-(this.days*86400)),3600);
this.mins = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)),60);
this.secs = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)-(this.mins*60)),1);
}
countDown.prototype.update=function(){
this.calculate();
$("#countdown-day").html(this.days + (this.days == 1));
$("#countdown-hour").html(this.hours + (this.hours == 1));
$("#countdown-min").html(this.mins + (this.mins == 1));
$("#countdown-sec").html(this.secs + (this.secs == 1));
var self = this;
setTimeout(function(){self.update();}, (1000));
}
function counterInit() {
var month = $("#d-month").html();
var day = $("#d-day").html();
var year = $("#d-year").html();
var time = $("#d-time").html();
new countDown( month + day + "," + year + time);
// new countDown('May 9, 2015, 00:00:00', 'counter'); }
}
counterInit();
}
});
I tried your fiddle and I can tell you there are some blank spaces at the end of each string which makes them differ between each other.
So If you just add these lines it will work
tDate = jQuery.trim(tDate);
eDate = jQuery.trim(eDate);
Here's your fiddle updated
http://jsfiddle.net/c5qkm5gL/
Edit:
I forgot to mention that I changed '.html()' to '.text()', this way you get the plain text instead of the html content.
As an advice, for debugging use console.log instead of an alert.

How to read dates (Birth) with google contacts service

Sorry for my poor english...
I try to read informations in my contacts with Google Apps Script - Contacts Service.
No problem with Name, Email, Adress, Phones, but I can't read dates (i want to get date of birth of my contacts).
How to read the "DateField"?
for (var i=0; i<contacts.length; i++) {
Name = contacts[i].getFullName();
EmailArray = contacts[i].getEmails(ContactsApp.Field.HOME_EMAIL);
if (EmailArray.length)
Email = contacts[i].getEmails(ContactsApp.Field.HOME_EMAIL)[0].getAddress();
if (!Email){
EmailArray = contacts[i].getEmails(ContactsApp.Field.WORK_EMAIL);
if (EmailArray.length)
Email = contacts[i].getEmails(ContactsApp.Field.WORK_EMAIL)[0].getAddress();
}
AddressArray = contacts[i].getAddresses(ContactsApp.Field.HOME_ADDRESS);
for ( var j = 0; j < AddressArray.length; j++ ) {
Address = AddressArray[j].getAddress();
AddressSplit = Address.split(/\r\n|\r|\n/);
Rue = AddressSplit[0];
Code = AddressSplit[1].split(" ")[0];
Ville = AddressSplit[1].split(" ")[1];
}
var HomePhone = contacts[i].getHomePhone();
var MobilePhone = contacts[i].getMobilePhone();
//HERE IS THE PROBLEM
DatesArray = contacts[i].getDates();
// Never pass here... How to read the DateField ?
for ( var j = 0; j < DatesArray.lenght; j++ ) {
var date = contacts[i].getDates()[j];
var day = date.getDay();
var month = date.getMonth();
var year = date.getYear();
}
}
I find the solution... after a moment !
Contacts services is not documented...
var dateArray = new Array(), day, month = new String, year;
var monthArray = ["0", "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
dateArray = contacts[i].getDates(ContactsApp.Field.BIRTHDAY);
for(var j in dateArray){
day = dateArray[j].getDay();
month = monthArray.indexOf(dateArray[j].getMonth().toString());
year = dateArray[j].getYear();
sheet.getRange(1*i+2, 3, 1, 1).setValue(day + "/" + month + "/" + year);
}
This should do it
DatesArray.length

Convert dates string to different format with javascript

This is what I have in a script that is pulling events with a Google Calendar API:
var datestring2 = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
After I append this to a list it prints out in the format 12/2 while I want it to print out Friday, Dec 2.
How can I do this? I have looked into date.js but had no luck.
There is no built in function in Javascript that can do that (I presume you are after something like PHP's date() function).
You can certainly roll your own solution as other answers have suggested, but unless you are really against it, date.js is great for this.
You can use the libraries toString() function to get formatted date strings like so:
Date.today().toString("d-MMM-yyyy");
More information can be found in the DateJS API documention.
You need something like:
var months = ['January', 'February', 'March', ...];
var ordinals = {1:'st', 21:'st', 31:'st', 2:'nd', 22:'nd', 3:'rd', 23:'rd'};
var m = startJSDate.getMonth();
var d = startJSDate.getDate();
var s = months[m] + ', ' + s + (ordinals[s] || 'th');
This article has some great examples on printing out dates in javacript
And from there you want something like this
var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
{
sup = "st";
}
else if (curr_date == 2 || curr_date == 22)
{
sup = "nd";
}
else if (curr_date == 3 || curr_date == 23)
{
sup = "rd";
}
else
{
sup = "th";
}
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
datestring2 = d_names[curr_day] + ", " + m_names[curr_month] + " " + curr_date + sup );
Will give you Thursday, December 1st

Javascript display/calculate past 3 months

I have a function that works out the past 3 months and displays the name by using an array.
I've just realised that when the new year comes round, for January, February & March, it won't be able to get the correct month.
I want to be able to do this without having to add in a hack (which is the only way I've seen to do this)
function getMonths()
{
var today = new Date();
var month = 0;
var currMonth = month-3;
var monthArray = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
var menuMonths = new Array();
var count = 4;
var buffer = 10;
while(count >0)
{
var month = monthArray[currMonth];
alert(currMonth);
menuMonths.push(month);
currMonth = currMonth +1;
count = count -1;
}
return menuMonths;
}
Modulus is your friend. Try:
function getMonths()
{
var today = new Date();
var month = 1;
var monthArray = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
var menuMonths = new Array();
for(var count = 3; count >= 0; count--)
menuMonths.push(monthArray[((12 + month - count) % 12)]);
return menuMonths;
}
alert(getMonths());
This little addition to your while-loop will ensure that currMonth is always a valid index of your monthArray:
while(count >0)
{
if (currMonth < 0)
currMonth += 12;
if (currMonth >=12 )
currMonth -= 12;
var month = monthArray[currMonth];
menuMonths.push(month);
currMonth = currMonth +1;
count = count -1;
}
working example: http://jsfiddle.net/RWhN4/
This is a bit hackish, but it should do what you want.
To figure out which month was 3 months ago you could do the following:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var monthIndex = d.getMonth() //(0-11)
Let standard javascript methods do the calculations for you.
Here is your function updated to use the javascript methods to do the calculations for you:
function getMonths() {
var date = new Date();
//subttract 3 months
date.setMonth(0 - 3);
var monthArray = new Array("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December");
var menuMonths = new Array();
var count = 4;
var buffer = 10;
while (count > 0) {
var month = monthArray[date.getMonth()];
alert(month);
menuMonths.push(month);
date.setMonth(date.getMonth() + 1);
count -= 1;
}
return menuMonths;
}
I did something similar to what you guys did, but I did it for the Trailing Twelve Months basically, in it's form format I used the following code:
$(".monthly_usage").val('');
var monthArray = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var today = new Date();
var month = today.getMonth();
var year = today.getFullYear();
var output = "Enter Trailing Twelve Months Usage<br/><center><table border=1 cellpadding=10 cellspacing=0><thead><th>Month - Year</th><th>Usage</th></thead><tbody>";
for(var i = 0; i < 12; i++) {
output += "<tr><td>" + monthArray[today.getMonth()] + " " + year + "</td><td><input type=text class=monthly_usage name=usage[]></td></tr>";
var month = today.setMonth(today.getMonth() - 1);
var year = today.getFullYear();
}
output += "</tbody></table>"+
"<button id=submit_ttm>Submit Monthly Usage</button></center>";
return output;
function lastMonths(count,month,order) {
var arr = [];
//defaults
month = typeof month !== 'undefined' ? month : new Date().getMonth();
count = typeof count !== 'undefined' ? count : 3;
order = typeof order !== 'undefined' ? order : "asc";
while (count-- > 0) {
month = (--month < 0) ? 11 : month;
arr.push(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][month]);
}
return ( order === "asc" ) ? arr.reverse() : arr;
}
the function has defaults for the number of months to show, the start month, and the order
demo

Categories

Resources