How to Populate An Array of Month Number In jQuery - Javascript - javascript

Can you please take a look at this demo and let me know how I can dynamically populate the number of each month for current year in jQuery or JavaScript?
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var daysInMonth = [];
var d = new Date();
var n = d.getMonth();
for (var i = 0; i < monthNames.length; i++) {
daysInMonth.push(d.getMonth());
}
console.log(daysInMonth);

var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var daysInMonth = [];
for (var i = 0; i < monthNames.length; i++) {
var year = 2014;
var month = new Date(monthNames[i] + " 01 "+ year).getMonth() + 1;
daysInMonth.push(new Date(year, month, 0).getDate());
}
console.log(daysInMonth);
DEMO http://jsfiddle.net/0mj2cxmt/7/

#Sam Battat's answer works too, but for a simple snippet of code that works on any year when called you could try this:
var thisDay = new Date();
var thisYear = thisDay.getYear();
var feb29th = new Date(thisYear, 1, 29);
var febDays = ((feb29th.getMonth() === 1) ? 29 : 28);
var dayCounts = [31,febDays,31,30,31,30,31,31,30,31,30,31];
Notes:
The number of days is hard coded for all months except February since they don't change
The feb29th variable above will actually become March 1st on years that don't have 29 days (e.g. non-leap years) and thus the month won't be "1"... defaulting the number of days back to 28
Update:
After running this perf test http://jsperf.com/leap-year-check it has become apparent that the "crafty" check for a leap year performance is nowhere near as good as basic math checks.
Thus I'd consider this to be even more efficient.
var thisDay = new Date();
var thisYear = thisDay.getYear();
var febDays = 28;
if((thisYear % 4 == 0) && (thisYear % 100 != 0) || (thisYear % 400 == 0)){
febDays = 29;
}
var dayCounts = [31,febDays,31,30,31,30,31,31,30,31,30,31];

Related

Display all 12 months serially but starting from the current month

I am working on a requirement where I have 12 ion slides and the names of the slides are month names starting from the current month. For ex: If the current month is June, then the name of the first slide should start from June 2020 and go on till May 2021. Well I tried it but not able to achieve. Even if I handle the month, then I am not able to dynamically change the year after December. Here is my code:
my html file
<ion-toolbar class="toolbars" #ionDragFooter>
<ion-title class="ion-text-center">{{currValue}}</ion-title>
</ion-toolbar>
My .ts file
ngOnInit() {
swipeNext()
}
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var d = new Date();
if(index == 1){
var curMn=monthNames[d.getMonth()]+ d.getFullYear();
console.log(curMn)
this.currValue=curMn;
}
else if(index == 2){
var curMn=monthNames[d.getMonth()+1]+ d.getFullYear();
this.currValue=curMn;
}
else if(index == 3){
var curMn=monthNames[d.getMonth()+2]+ d.getFullYear();
this.currValue=curMn;
}
and so on for all other month. I need to completely automate the month and year starting from the current month. May I know where I went wrong?
You can create a date, then increment the month by 1 eleven times to get 12 months of dates. The month name can be found using toLocaleString with appropriate options.
You need to be careful when incrementing months, e.g.
let d = new Date(2020,0,31); // 31 Jan 2020
d.setMonth(d.getMonth() + 1) // 31 Feb 2020 -> 2 Mar 2020
d.toDateString(); // Mon Mar 02 2020
So best to set the date to the 1st of the month initially:
// Optionally provide a date for the starting month
function getMonthNames(date = new Date()) {
// Copy input date so don't modify it
let d = new Date(+date);
// Set to 1st of month
d.setDate(1);
let result = [];
// Get 12 month names, starting with current month
for (let i=0; i<12; i++) {
result.push(d.toLocaleString('default',{month:'long'}));
d.setMonth(d.getMonth() + 1);
}
return result;
}
console.log(getMonthNames());
To properly change the date you have to increase the date by the amount of months in the date object (in your case d):
var d = new Date();
//REM: This will print out the next month, yet d still is unchanged
console.log(d.getMonth()+1);
console.log(d);
console.log('Month did not increase: ', d.getMonth());
//REM: You have to increase your date by one month in the date object
d.setMonth(d.getMonth() + 1);
console.log(d);
console.log('Month did increase: ', d.getMonth());
//REM: By which it will change the year for you, once it is time for it.
d.setMonth(d.getMonth() + 11); //REM: +1 from before
console.log(d);
console.log('Year did increase: ', d.getFullYear());
In your case that would be:
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var d = new Date();
d.setDate(1); //REM: To prevent month skipping.
for(var i=0; i<12; i++){
d.setMonth(d.getMonth() + 1);
console.log(monthNames[d.getMonth()], d.getFullYear())
};
Some further reading on the issue
This is what I came up with:
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
const today = new Date();
//gives you year
const year = today.getFullYear();
//gives you month as number/index;
const month = today.getMonth();
//stores sequenced month names
const sequencedNames = [];
//creates June 2020 through December 2020
for(let i = month; i < monthNames.length; i++) {
let monthName = monthNames[i];
sequencedNames.push(monthName + " " + year)
}
//creates January 2021 through May 2021
for(let i = 0; i < month; i++) {
let monthName = monthNames[i];
sequencedNames.push(monthName + " " + (year + 1))
}
console.log(sequencedNames)
Essentially 2 for loops, the first iterating from the current month to the end of the year, and then the second from the start of the year to the current month -- though adding 1 year.

problem while creating dynamic labels for chart js

I am creating dynamic labels for the chart js by supplying range of the month . It is working good if i selected start month and end month in ascending order but it is not working in the case where i selected start month = december and end month = march.
Here is my code ,
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March']; // here i give the lower and upper limit for the label
for (var i = monthNames.indexOf(monthn[0]); i <= monthNames.indexOf(monthn[1]); i++) {
monthArr.push(monthNames[i]);
}
return monthArr;
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March'];
if (monthNames.indexOf(monthn[1]) < monthNames.indexOf(monthn[0])) {
monthNames.unshift(monthNames.splice(monthNames.indexOf(monthn[0]), 1)[0]);
for (var i = monthNames.indexOf(monthn[0]); i <= diff; i++) {
monthArr.push(monthNames[i]);
}
} else {
for (var i = monthNames.indexOf(monthn[0]); i <= monthNames.indexOf(monthn[1]); i++) {
monthArr.push(monthNames[i]);
}
}
return monthArr;
Try to validate the index between the two months
Here is an example with your code and a very small changes.
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March']; // here i give the lower and upper limit for the label
// make sure that StartMonth is smaller then Endmonth
var startMonth = monthNames.indexOf(monthn[0]) <= monthNames.indexOf(monthn[1]) ? monthNames.indexOf(monthn[0]) : monthNames.indexOf(monthn[1]);
// make sure that EndMonth is bigger then StartMonth
var endMonth = monthNames.indexOf(monthn[0]) <= monthNames.indexOf(monthn[1]) ? monthNames.indexOf(monthn[1]) : monthNames.indexOf(monthn[0]);
for (var i = startMonth; i <= endMonth; i++) {
monthArr.push(monthNames[i]);
}
// Add the missing months
if (startMonth -1 >0)
{
for (var i = 0; i <= startMonth -1; i++) {
monthArr.push(monthNames[i]);
}
}
console.log(monthArr)

Day and year with javascript

i'm doing a program which, given the day of the year, estabilishes day and month.
I wrote this code, but it doesn't work when the input is >31.
I hope that someone will help me, thank you.
<script>
var dayn=[31,28,31,30,31,30,31,31,30,31,30,31];
var vettmonth=["January", "February", "March", "April", "May","June","July","August","September","October","November","Dicember"];
function f()
{
var nday, day, month, count=0;
nday=eval(ngiorno.value);
for(var i=0;i<12;i++){
if (nday>dayn[i]){
count=count+dayn[i]; }
else if(nday<32){
day=nday;
month=vettmonth[i];
break;
}
else if(nday>31 && nday<dayn[i+1]+count){
day=nday-count;
month=vettmonth[i+1];
break;
}
}
mmese.value=month;
ggiorno.value=day;
}
</script>
The problem is that you're never reducing nday as you go through the months. So if nday > 31, nday > dayn[i] will be true every time, and you'll never execute the else if blocks that set day and month. You need to subtract dayn[i] from nday.
There's no need for two else if blocks. When the if block fails you're in the correct month. And the count variable is not needed, either.
var dayn = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var vettmonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function f(nday) {
var day, month;
var daynum = nday;
for (var i = 0; i < dayn.length; i++) {
if (nday > dayn[i]) {
nday -= dayn[i];
} else {
day = nday;
month = vettmonth[i];
break;
}
}
console.log(`${daynum} = ${month} ${day}`);
}
f(10)
f(32);
f(150);
f(360);
You've made this more complicated then it has to be. You can do something like this:
const vettmonth=["January", "February", "March", "April", "May","June","July","August","September","October","November","Dicember"];
let dayOfTheYear = 120;
let date = new Date(new Date().getFullYear(), 0, 1); // Start of this year
date.setDate(120); // increase the date by "dayOfTheYear"
console.log("Month:",vettmonth[date.getMonth()], "Day:", date.getDate());
If you need to do this without using Date objects, you can do it like this:
const dayn = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const vettmonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let dayOfTheYear = 120;
let monthIndex = 0;
let day = 0;
for(let i = 0, sum = 0; i < dayn.length; i++){
sum+=dayn[i];
if(dayOfTheYear <= sum){
monthIndex = i;
day = (sum - dayOfTheYear) + 1;
break;
}
}
console.log("Month:", vettmonth[monthIndex], "Day:", day);

Coverting DATETIME string to time and date in words Javascript or jQuery

i have a datetime parameter in a string from an JSON object
like this-
datetime:"2015-04-15 09.00.00"
my goal is to convert it to:
"15 April 09:00"
(2015 can be included as well but not necessary)
After i will append in in 2 different places, date and time.
Any suggestions? Can't seem to find any good info apart from getting a plugin.
You can parse the month like the answer here:
https://stackoverflow.com/a/1643468/2498251
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
so for your case you can make something like this:
var d = new Date("2015-04-15 09:00:00");
var day = d.getDay();
var month = monthNames[d.getMonth()];
var year = d.getYear();
var hour = d.getHours();
var min = d.getMinutes();
var fullDatetime = day + ' ' + month + ' ' + hour + ':' + min;

Enter date into HTML onload Javascript

I am trying to enter the current date when the page loads. I am able to store it to a variable, I am just having trouble entering that variable onto the page.
HTML:
<span id='test'>x</span>
Javascript:
window.onload = function() {
var month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var currentMonth = month[mm];
var yyyy = today.getFullYear();
today = currentMonth + ' ' + dd + ', ' + yyyy;
document.getElementById('test').innertext() = today;
}
JSFIDDLE
Change this:
document.getElementById('test').innertext() = today;
for this:
document.getElementById('test').innerHTML = today;
Use this code, it works
window.onload = function() {
var month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var currentMonth = month[mm];
var yyyy = today.getFullYear();
today = currentMonth + ' ' + dd + ', ' + yyyy;
document.getElementById('test').innerHTML = today;
}
You have a problem at the following line of code because you treat the innerText property as if it was a function and you don't camel-case it (JavaScript is a case-sensitive language):
document.getElementById('test').innertext() = today;
So change it to:
document.getElementById('test').innerText = today;
Here is the working example: http://jsfiddle.net/ynevet/cNCf4/

Categories

Resources