How to get month in previous year? - javascript

I try to get the previous month according to current month. But the problem occurs when "year" is not 2017.
So how can I get the month of the previous year?. The code below will describe what I want, if anybody know how to get it please tell me the method. Thank you :)
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var cur_month = new Date();
var cur_month_now = month[cur_month.getMonth()];
var pre_month_1 = month[cur_month.getMonth()-1];
var pre_month_2 = month[cur_month.getMonth()-2];
var pre_month_3 = month[cur_month.getMonth()-3];
var pre_month_4 = month[cur_month.getMonth()-4];
var pre_month_5 = month[cur_month.getMonth()-5];
document.getElementById("cur_month").innerHTML = cur_month_now;
document.getElementById("pre_month_1").innerHTML = pre_month_1;
document.getElementById("pre_month_2").innerHTML = pre_month_2;
document.getElementById("pre_month_3").innerHTML = pre_month_3;
document.getElementById("pre_month_4").innerHTML = pre_month_4;
document.getElementById("pre_month_5").innerHTML = pre_month_5;
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">Select Month
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>

You are getting this undefined because month[-1] and month[-2] are undefined
You need to actually do date manipulation in a date object rather than just getting date from index.
Use this method to get last month date
function getPrevMonth(date) {
date.setMonth(date.getMonth() - 1);
return date;
}
invoke this method as many times as you need.
Demo
function getPrevMonth(date) {
date.setMonth(date.getMonth() - 1);
return date;
}
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var cur_month = new Date();
var cur_month_now = month[cur_month.getMonth()];
var pre_month_1 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_2 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_3 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_4 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_5 = month[getPrevMonth(cur_month).getMonth()];
document.getElementById("cur_month").innerHTML = cur_month_now;
document.getElementById("pre_month_1").innerHTML = pre_month_1;
document.getElementById("pre_month_2").innerHTML = pre_month_2;
document.getElementById("pre_month_3").innerHTML = pre_month_3;
document.getElementById("pre_month_4").innerHTML = pre_month_4;
document.getElementById("pre_month_5").innerHTML = pre_month_5;
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">Select Month
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
</div>

Let Date do the wrap-around for you. There are also a couple of improvements we can make to the code, see comments:
// Array initializers are cleaner and less typing
var month = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
var dt = new Date();
var cur_month_now = month[dt.getMonth()];
dt.setMonth(dt.getMonth() - 1); // Date handles wrapping to previous year
var pre_month_1 = month[dt.getMonth()];
dt.setMonth(dt.getMonth() - 1);
var pre_month_2 = month[dt.getMonth()];
dt.setMonth(dt.getMonth() - 1);
var pre_month_3 = month[dt.getMonth()];
dt.setMonth(dt.getMonth() - 1);
var pre_month_4 = month[dt.getMonth()];
dt.setMonth(dt.getMonth() - 1);
var pre_month_5 = month[dt.getMonth()];
document.getElementById("cur_month").innerHTML = cur_month_now;
document.getElementById("pre_month_1").innerHTML = pre_month_1;
document.getElementById("pre_month_2").innerHTML = pre_month_2;
document.getElementById("pre_month_3").innerHTML = pre_month_3;
document.getElementById("pre_month_4").innerHTML = pre_month_4;
document.getElementById("pre_month_5").innerHTML = pre_month_5;
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">Select Month
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
</div>

Nothing really new, but for smaller js code …
function getPrevMonth(date, m) {
date.setMonth(date.getMonth() - m);
return date;
}
//no need for such array
locale = "en-us";//or e.g. navigator.languages[0]
var d = new Date();
for (var i=0; i<6; i++){
//also worth trying: create element instead of writing to exiting ones only: https://www.w3schools.com/jsref/met_document_createelement.asp
document.getElementById("pre_month_"+i).innerHTML = getPrevMonth(d,1).toLocaleString(locale, { month: "long" });
}
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">Select Month
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
</div>

You could do this a bit more concise, and using modulo operator:
var month = "January,February,March,April,May,June,July,August,September,October,November,December"
.split(','),
monthNum = 12 + new Date().getMonth();
Array.from(document.querySelectorAll('.dropdown-menu a'), function (elem, i) {
elem.textContent = month[(monthNum-i)%12];
});
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">Select Month
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
NB: It is better practice to use textContent instead of innerHTML, since you want to put text, not HTML.

Related

Open a Comment section when pressing a date in a calendar

I have made a Calendar and a Comment section, and my goal is to open the comment section when pressing a date, and make the date change colour when a comment is witten on a certain date.
I will later on work on the backend to be able to manage all the comments, so they stay on the set day. Now Im only worried about opening the comments.
Do I need to make all the items into buttons for this to work, or is it possible with js?
<div class="calendar__container">
<div class="calendar__wrapper">
<header>
<p class="current-date"></p>
<div class="icons">
<span id="prev" class="material-symbols-rounded">❮</span><span id="next" class="material-symbols-rounded">❯</span>
</div>
</header>
<div class="calendar">
<ul class="weeks">
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
<li>Sun</li>
</ul>
<ul class="days">
<li class="inactive">9</li>
<li class="active">10</li>
<li>11</li>
<li>12</li>`your text`
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li>20</li>
<li>21</li>
</ul>
</div>
</div>
<div class="comment__container">
<div class="comment__main">
<h2>Plan Your days</h2>
<form>
<textarea placeholder="Your Task"></textarea>
<div class="btn">
<input type="submit" value="Add Task">
<button>Cancel</button>
</div>
</form>
</div>
</div>
//Calendar and Comment JS//
const daysTag = document.querySelector(".days"),
currentDate = document.querySelector(".current-date"),
prevNextIcon = document.querySelectorAll(".icons span");
let date = new Date(),
currYear = date.getFullYear(),
currMonth = date.getMonth();
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const renderCalendar = () => {
let firstDayofMonth = new Date(currYear, currMonth, 1).getDay(),
lastDateofMonth = new Date(currYear, currMonth + 1, 0).getDate(),
lastDayofMonth = new Date(currYear, currMonth, lastDateofMonth).getDay(),
lastDateofLastMonth = new Date(currYear, currMonth, 0).getDate();
let liTag = "";
for (let i = firstDayofMonth; i > 0; i--) {
liTag += `<li class="inactive">${lastDateofLastMonth - i + 1}</li>`;
}
for (let i = 1; i <= lastDateofMonth; i++) {
let isToday =
i === date.getDate() &&
currMonth === new Date().getMonth() &&
currYear === new Date().getFullYear()
? "active"
: "";
liTag += `<li class="${isToday}">${i}</li>`;
}
for (let i = lastDayofMonth; i < 6; i++) {
liTag += `<li class="inactive">${i - lastDayofMonth + 1}</li>`;
}
currentDate.innerText = `${months[currMonth]} ${currYear}`;
daysTag.innerHTML = liTag;
};
renderCalendar();
prevNextIcon.forEach((icon) => {
icon.addEventListener("click", () => {
currMonth = icon.id === "prev" ? currMonth - 1 : currMonth + 1;
if (currMonth < 0 || currMonth > 11) {
date = new Date(currYear, currMonth, new Date().getDate());
currYear = date.getFullYear();
currMonth = date.getMonth();
} else {
date = new Date();
}
renderCalendar();
});
});
var feild = document.querySelector("textarea");
var backUp = feild.getAttribute("placeholder");
var btn = document.querySelector(".btn");
var clear = document.getElementById("clear");
feild.onfocus = function () {
this.setAttribute("placeholder", "");
this.style.borderColor = "#333";
btn.style.display = "block";
};
feild.onblur = function () {
this.setAttribute("placeholder", backUp);
this.style.borderColor = "#aaa";
};
clear.onclick = function () {
btn.style.display = "none";
feild.value = "";
};

Choose the current month

I have a check box with value for month I want to check the current month.
var d = new Date(),
n = d.getMonth(),
y = d.getFullYear();
console.log(n);
$("input[name='month[]']").each(function() {
$(this).val().split("_");
console.log($(this).val().split("-")[0]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="checklist">
<li tabindex="0" class="even"><input type="checkbox" value="April-2020" name="month[]" id="month_April_2020"><label for="month_April_2020" class="leaveRoomForCheckbox">April-2020</label></li>
<li tabindex="0" class="odd"><input type="checkbox" value="May-2020" name="month[]" id="month_May_2020"><label for="month_May_2020" class="leaveRoomForCheckbox">May-2020</label></li>
<li tabindex="0" class="even"><input type="checkbox" value="June-2020" name="month[]" id="month_June_2020"><label for="month_June_2020" class="leaveRoomForCheckbox">June-2020</label></li>
</ul>
I want to checked the 'May 2020' based on current year last month.
You need a map of the months' indices to their names, then it's simple to identify the previous month, given its index:
const monthsNames = ['January', 'February', 'Match', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var d = new Date(),
n = d.getMonth(),
y = d.getFullYear();
const previousMonthName = monthsNames[n-1];
$("input[name='month[]']").each(function() {
const monthName = $(this).val().split("-")[0];
if (monthName === previousMonthName) {
$(this).attr('checked', 'checked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="checklist">
<li tabindex="0" class="even"><input type="checkbox" value="April-2020" name="month[]" id="month_April_2020"><label for="month_April_2020" class="leaveRoomForCheckbox">April-2020</label></li>
<li tabindex="0" class="odd"><input type="checkbox" value="May-2020" name="month[]" id="month_May_2020"><label for="month_May_2020" class="leaveRoomForCheckbox">May-2020</label></li>
<li tabindex="0" class="even"><input type="checkbox" value="June-2020" name="month[]" id="month_June_2020"><label for="month_June_2020" class="leaveRoomForCheckbox">June-2020</label></li>
</ul>
You can compare current with your value and set checked as
if(month == currentMonth){
$(this).attr('checked', 'checked')
}
var d = new Date(),
n = d.getMonth(),
y = d.getFullYear();
console.log(n);
$("input[name='month[]']").each(function() {
$(this).val().split("_");
var month = $(this).val().split("-")[0];
var currentMonth = getMonth(new Date());
//alert(month);
if(month == currentMonth){
$(this).attr('checked', 'checked')
}
});
function getMonth(d){
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
return month[d.getMonth()];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="checklist">
<li tabindex="0" class="even"><input type="checkbox" value="April-2020" name="month[]" id="month_April_2020"><label for="month_April_2020" class="leaveRoomForCheckbox">April-2020</label></li>
<li tabindex="0" class="odd"><input type="checkbox" value="May-2020" name="month[]" id="month_May_2020"><label for="month_May_2020" class="leaveRoomForCheckbox">May-2020</label></li>
<li tabindex="0" class="even"><input type="checkbox" value="June-2020" name="month[]" id="month_June_2020"><label for="month_June_2020" class="leaveRoomForCheckbox">June-2020</label></li>
</ul>
You could update the ids of the checkboxes to the matching index of a month and do the following:
const date = new Date();
const monthIndex = date.getMonth();
const year = date.getFullYear();
$(`#${monthIndex}`).prop("checked", true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="checklist">
<input type="checkbox" value="April-2020" id="3"><label>April-2020</label>
<input type="checkbox" id="4" value="May-2020"><label>May-2020</label>
<input type="checkbox" value="June-2020" id="5"><label>June-2020</label>
</ul>
This should work.
var d = new Date(),
n = d.getMonth(),
y = d.getFullYear();
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var currentDate = month[n] + '-' + y;
$("input[name='month[]']").each(function() {
$(this).val().split("_");
console.log($(this).val().split("-")[0]);
});
$(`input[type=checkbox][value=${currentDate}]`).prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="checklist">
<li tabindex="0" class="even"><input type="checkbox" value="April-2020" name="month[]" id="month_April_2020"><label for="month_April_2020" class="leaveRoomForCheckbox">April-2020</label></li>
<li tabindex="0" class="odd"><input type="checkbox" value="May-2020" name="month[]" id="month_May_2020"><label for="month_May_2020" class="leaveRoomForCheckbox">May-2020</label></li>
<li tabindex="0" class="even"><input type="checkbox" value="June-2020" name="month[]" id="month_June_2020"><label for="month_June_2020" class="leaveRoomForCheckbox">June-2020</label></li>
</ul>
Find the current date, then set a new date with the last month, next get month name using ECMAScript International API
Then check which month is the most recent month
var d = new Date(),
newDate = new Date(d.setMonth(d.getMonth() - 1)),
lastMonth = newDate.toLocaleString('default', { month: 'long' });
$("input[name='month[]']").on('change', function()
{
$(this).filter(':checked').each(function(){
$(this).val().split("_")[0];
console.log($(this).val().split("-")[0]);
if ($(this).val().split("-")[0] == lastMonth )
{
console.log(`${$(this).val().split("-")[0]} is the last month`);
}
});
});

How can i refresh and/or hide script content

Good evening! I have an assignment in school that requires me to:
Add a button that switches language from spanish to english.
And changing the DD:MM:YY Format, so i made a switch that changes them with each press of the button.
The problem is..... using this script...
'''
var inicioTiempo=0;
function fechaHora()
{
var cont=0;
dt=new Date();
var dia=["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"];
var mes=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
var hora=["12","1","2","3","4","5","6","7","8","9","10","11","12","1","2","3","4","5","6","7","8","9","10","11"];
var fyh=" "+dia[dt.getDay()]+" ";
switch (cont) {
case 0:
fyh=fyh+mes[dt.getMonth()]+" ";
fyh=fyh+dt.getDate()+" ";
fyh=fyh+dt.getFullYear();
cont=cont+1;
break;
case 1:
fyh=fyh+dt.getDate()+" ";
fyh=fyh+mes[dt.getMonth()]+" ";
fyh=fyh+dt.getFullYear();
cont=cont+1;
break;
case 2:
fyh=fyh+dt.getFullYear()+" ";
fyh=fyh+mes[dt.getMonth()]+" ";
fyh=fyh+dt.getDate();
cont=cont+1;
break;
case 3:
fyh=fyh+dt.getFullYear()+" ";
fyh=fyh+dt.getDate()+" ";
fyh=fyh+mes[dt.getMonth()];
cont=0;
break;
}
fyh=fyh+" <br> "+hora[dt.getHours()]+":"+dt.getMinutes()+":"+dt.getSeconds();
if(dt.getHours()>=0 && dt.getHours()<=11)
fyh=fyh+" a.m.";
else
fyh=fyh+" p.m. ";
document.getElementById('labelFechaHora').innerHTML=fyh;
setTimeout("fechaHora()",100);
}
</script>
<body onLoad="fechaHora()" link="black" alink="black" vlink="black">
<div class="panel panel-default">
<div class="panel-body">
<center>
<br>
<font color="black"> <label id="labelFechaHora"/> </font> <br>
<font color="black"> <label id="labelFechaHoraENG"/> </font> <br>
<input type="button" value="Ingles" onclick="fechaHoraENG();">
<input type="button" value="Español" onclick="fechaHora();">
'''
When i try to press once again the button, the script does not change at all, and the other one remains there.
1- Edit so that: Each time i press the spanish/eng, one shows up and hides the other.
2- When i re'press, the DD:MM:YY change (Asuming i had one function per language)
Below is an example of Object Oriented, mixed with Functional, Programming in JavaScript. I decided you didn't really want just an increment that is looped over time. Instead you want to be able to select a language and a format.
function FechaHora(){
let dt = new Date;
const dia = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
const mes = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
this.updateDate = ()=>{
dt = new Date;
return this;
}
const formatIt = (format, array)=>{
let m = array[dt.getMonth()], d = dt.getDate(), y = dt.getFullYear();
switch(format.toLowerCase()){
case 'mdy':
return m+' '+d+' '+y;
case 'dmy':
return d+' '+m+' '+y;
case 'ymd':
return y+' '+m+' '+d;
case 'ydm':
return y+' '+d+' '+m;
}
}
this.fechaDia = format=>{
return formatIt(format, dia);
}
this.fechaMes = format=>{
return formatIt(format, mes);
}
this.fechaTime = ()=>{
let h = dt.getHours(), m = dt.getMinutes(), s = dt.getSeconds(), p = 'a.m.';
if(h > 12){
h -= 12; p = 'p.m.';
}
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
return h+':'+m+':'+s+' '+p;
}
}
let doc, html, bod, I; // for use on other loads
addEventListener('load', ()=>{
doc = document; html = doc.documentElement; bod = doc.body; I = id=>doc.getElementById(id);
const date = I('date'), time = I('time'), lang = I('lang'), format = I('format');
const fa = new FechaHora;
let ti;
function output(){
let v = format.value;
fa.updateDate();
switch(lang.value){
case 'dia':
date.textContent = fa.fechaDia(v);
break;
case 'mes':
date.textContent = fa.fechaMes(v);
break;
}
time.textContent = fa.fechaTime();
}
function run(milliseconds = 1000){
if(ti)clearInterval(ti);
output(); ti = setInterval(output, milliseconds);
}
run();
lang.onchange = format.onchange = e=>{
run();
}
}); // end load
*{
box-sizing:border-box;
}
<div id='date'></div>
<div id='time'></div>
<select id='lang'>
<option value='dia'>Dia</option>
<option value='mes'>Mes</option>
</select>
<select id='format'>
<option value='mdy'>M D Y</option>
<option value='dmy'>D M Y</option>
<option value='ymd'>Y M D</option>
<option value='ydm'>Y D M</option>
</select>

Order a list of calendar events in Javascript and add month name

I have a list of events in HTML:
<ol id="my-list">
<li data-start="01-Jan-2019">Event on 01-Jan-2019</li>
<li data-start="25-Dec-2018">Event on 25-Dec-2018</li>
<li data-start="14-Feb-2018">Event on 14-Feb-2018</li>
<li data-start="14-Jul-2019">Event on 14-Jul-2019</li>
<li data-start="31-Oct-2019">Event on 31-Oct-2019</li>
<li data-start="13-Oct-2019">Event on 13-Oct-2019</li>
<li data-start="26-Oct-2016">Event on 26-Oct-2016</li>
<li data-start="02-Dec-2018">Event on 02-Dec-2018</li>
<li data-start="21-Dec-2018">Event on 21-Dec-2018</li>
<li data-start="18-Dec-2018">Event on 18-Dec-2018</li>
</ol>
How can I modify the list to be:
<ol id="my-list">
<span>October</span>
<li data-start="01-Jan-2019">Event on 26-Oct-2016</li>
<span>February</span>
<li data-start="25-Dec-2018">Event on 14-Feb-2018</li>
<span>December</span>
<li data-start="14-Feb-2018">Event on 02-Dec-2018</li>
<li data-start="14-Jul-2019">Event on 18-Dec-2018</li>
<li data-start="31-Oct-2019">Event on 21-Dec-2018</li>
<li data-start="13-Oct-2019">Event on 25-Dec-2018</li>
<span>January</span>
<li data-start="26-Oct-2016">Event on 01-Jan-2019</li>
<span>July</span>
<li data-start="02-Dec-2018">Event on 14-Jul-2019</li>
<span>October</span>
<li data-start="21-Dec-2018">Event on 13-Oct-2019</li>
<li data-start="18-Dec-2018">Event on 31-Oct-2019</li>
</ol>
I can also use jQuery.
More specifically, I need to compare each date and see if the month has changed, then if it is, append the right month name.
First I ordered the events (source http://jsfiddle.net/greguarr/2fr0vmhu/):
var container = $("#my-list");
var items = $("#my-list li");
items.each(function() {
// Convert the string in 'data-start' attribute to a more
// standardized date format
var BCDate = $(this).attr("data-start").split("-");
var standardDate = BCDate[1]+" "+BCDate[0]+" "+BCDate[2];
standardDate = new Date(standardDate).getTime();
$(this).attr("data-start", standardDate);
console.log($(this).attr("data-start", standardDate));
});
items.sort(function(a,b){
a = parseFloat($(a).attr("data-start"));
b = parseFloat($(b).attr("data-start"));
return a<b ? -1 : a>b ? 1 : 0;
}).each(function(){
container.append(this);
});
Then I want to compare each event month name with its previous event month name and insert the name of the month only if the month changed.
Compare the month of each event with the previous one and if it's different, append its name before the list item:
items.each(function(i) {
var a1 = new Date($(this).data('start'));
var b1 = new Date($(this).prev().data('start'));
if (a1.getMonth() != b1.getMonth()) {
$(this).before("<span>" + defineMonth(a1.getMonth()) + "</span>");
}
});
Where defineMonth is a function to retrieve the name of the month:
function defineMonth(evt) {
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var n = month[evt];
return n;
}

When I use Date() object in vue2, I found there is something very strange: getMonth +1 gets an error, and April have 31days

Why does this.currentMonth = mydate.getMonth()+1; show errow in vue?
And why does my month of April has 31 days? It seems that strday=now.getFullYear()+"-"+(now.getMonth()+1)+"-"+1; There is something wrong here, but I don't know how to correct it.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="jslib/vue.js"></script>
<link rel="stylesheet" href="css/semantic.min.css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<div id="calendar">
<div class="month">
<ul>
<li>
<span class="choose-year">{{ currentYear }}Year</span>
<span class="choose-month">{{ currentMonth }}Month</span>
</li>
</div>
<ul class="weekdays">
<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
<li>Thursday</li>
<li>Friday</li>
<li style="color:red">Saterday</li>
<li style="color:red">Sunday</li>
</ul>
<ul class="days">
<li v-for="dayobject in days">
<span v-if="dayobject.mydate.getMonth()+1 != currentMonth" class="other-month">{{ dayobject['mydate'].getDate() }}</span>
<span v-else>
<span v-if="dayobject['mydate'].getFullYear() == new Date().getFullYear() && dayobject['mydate'].getMonth() == new Date().getMonth() && dayobject['mydate'].getDate() == new Date().getDate()" class="active">{{ dayobject['mydate'].getDate() }}</span>
<span v-else>{{ dayobject['mydate'].getDate() }}</span>
</span>
</li>
</ul>
</div>
</body>
</html>
enter code here
<script>
var myVue=new Vue({
el: '#calendar',
data: {
currentDay: 1,
currentMonth: 1,
currentYear: 1970,
currentWeek: 1,
days: [],
},
created: function() {
this.initData(null);
},
methods: {
initData: function(cur) {
//My algorithm is:
//1 find the first day of the month,
//2 the date of fist day - day of the fist day, if May 1st is Tuesday, then set the fist day shown in calendar = (May 1st).getDate()-1;
//3 list 35days in my calender
var mydate;
if (cur) {
mydate = new Date(cur);
} else {
var now=new Date();
mydate = new Date(now.getFullYear(),now.getMonth());
};
this.currentDay = mydate.getDate();
this.currentYear = mydate.getFullYear();
this.currentMonth = mydate.getMonth();//here if : this.currentMonth = mydate.getMonth()+1; will get something wrong
if(mydate.getDay()==0)
{
mydate.setDate(mydate.getDate()-6);
}
else{
mydate.setDate(mydate.getDate()-mydate.getDay()+1);
};
//var str = this.formatDate(this.currentYear , this.currentMonth, 1);
this.days =[];
for (i=0; i <35; i++) {
var thisday=new Date();
thisday.setDate(mydate.getDate()+i);
dayobject={
'mydate':thisday
};
this.days.push(dayobject);
};
},
},
});
</script>
I want my calendar to show like this, but there a something strange shown.

Categories