Looping through each month between two years - javascript

My javascript is horrible, I am a C# dev but here we are. So I need to loop through every month between a start year and month to an end year and month.
The startMonth and startYear will always be 1 and 2010 respectively.
I have the following solution at the moment:
//Get the current year and month
let currentTime = new Date();
let currentYear = currentTime.getFullYear();
let currentMonth = currentTime.getMonth() + 1;
//Set starting year and month
let startYear = 2010;
let startMonth = 1;
//Loop through the years and months
for (let i = startYear; i <= currentYear; i++){
if (i === currentYear ){
for (let k = 1; k <= currentMonth; k++){
//Do work
}
} else {
for (let j = startMonth; j <= 12; j++){
//Do work
}
}
}
Does someone have a better solution? I feel like this is really clunky. I don't mind using third party packages so if moment or something will work then I'll use it.

Here is what you want :
const start = moment.utc('2018-12');
const end = moment.utc('2020-02');
const year = end.diff(start, 'years');
const month = end.diff(start, 'months')
console.log(start, end);
console.log(year, month);// 1 14
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

First off, be aware that months run from 0 to 11 so January is 0 not 1!
JavaScript's Date class automatically handles "overflows". So for example a date
new Date(2010, 12, 1)
automatically becomes "January 1st, 2011".
This can be used to simply increment just the month of a date:
const currentDate = new Date(2010, 0, 1);
const endDate = new Date();
endMonth.setMonth(endMonth.getMonth() + 1);
while (currentDate.getFullYear() != endMonth.getFullYear() && currentDate.getMonth() != endMonth.getMonth()) {
// Do something
currentDate.setMonth(currentDate.getMonth() + 1);
}
(Watch out that is could result in an endless loop if the start date is already after the end date.)

Here is a slight improvement without adding a third party library:
//Get the current year and month
let currentTime = new Date();
let currentYear = currentTime.getFullYear();
let currentMonth = currentTime.getMonth() + 1;
//Set starting year and month
let startYear = 2010;
let startMonth = 1;
//Loop through the years and months
for (let i = startYear; i <= currentYear; i++){
for (let j = startMonth; j <= (i == currentYear ? currentMonth: 12); j++){
//Do work
}
}

Related

How to find the days of the week in JavaScript

I am trying to find the weekdays from today to Sunday. Since today is Monday I want to display the dates from Monday till Sunday, but tomorrow, I want my programme works from Tuesday to Sunday.
dateSets() {
let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const diff = sunday.getDate() - firstDayOfWeek.getDate();
dates.push(new Date());
for (let i = 0; i < diff; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
}
return dates;
},
And here is the other function to find the date of the week:
getDateOfWeek(week, year) {
let simple = new Date(year, 0, 1 + (week - 1) * 7);
let dow = simple.getDay();
let weekStart = simple;
if (dow <= 4) weekStart.setDate(simple.getDate() - simple.getDay() + 1);
else weekStart.setDate(simple.getDate() + 8 - simple.getDay());
return weekStart;
},
But it doesn't work that I expected, in dataset, only Monday is being displayed but not other dates and I don't understand the reason. If you can help me with this, I would be really glad.
Thanks...
function getWeekDates(){
const dates = [new Date()]; // today
const curr = new Date();
const remDaysCount = 7-curr.getDay();
for(let i=1; i<= remDaysCount; i++){
// increase current Date by 1 and set to current Date
const nextDate = curr.setDate(curr.getDate()+1);
dates.push(new Date(nextDate));
}
return dates;
}
console.log(getWeekDates());
This is kind of your choice but if you install NodeJS and open your folder in cmd and type in 'npm init' and 'npm I days' and open your editor and type in
var days = require('days');
console.log(days); // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
console will reveal all of the days of the week and if you want a specific day you can do the following
var days = require('days');
console.log(days[0]); //Sunday
if you need help with installing NodeJS watch a YouTube video or reply to this comment I will help
let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
//const diff = sunday.getDate() - firstDayOfWeek.getDate();
//Try this code
var timeDiff = Math.abs(sunday.getTime() - firstDayOfWeek.getTime());
var diff = Math.ceil(timeDiff / (1000 * 3600 * 24));
dates.push(new Date());
for (let i = 0; i < diff; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
}
return dates;
Your issue is here:
const diff = sunday.getDate() - firstDayOfWeek.getDate()
Currently the date is 27 Sep and next Sunday is 3 Oct so diff is -4 and the for loop test i < diff is false from the start. Consider using a loop and increment the date from today until it gets to Sunday.
function getDaysToSunday(date = new Date()) {
let d = new Date(+date);
let result = [];
do {
result.push(new Date(+d));
d.setDate(d.getDate() + 1);
} while (d.getDay() != 1)
return result;
}
console.log(getDaysToSunday().map(d=>d.toDateString()));

How to generate array of years till current year?

In below code I can generate array of years but it's not dynamic. Year should start from 1901 to current year and in reverse order.
const theDates = [];
let cell = 1900;
for (let x = 0; x < 24; x += 1) {
const row = [];
for (let y = 0; y < 5; y += 1) {
row.push(cell += 1);
}
theDates.push(row.reverse());
}
console.log(JSON.stringify(theDates.reverse()).toString());
Currently, I am generating years till 2020 but I am hard-coding it. I need something like below, say that this is year 2023
[[2023,2022,2021,2020,2019], ... [1903,1902,1901,null,null]]
At any given point in time there should be 5 items in the inner array and last empty array values can be null
thanks in advance :)
Get the year with new Date().getFullYear(), then you can push chunks of 5 while the year number is greater than 1901:
const theDates = [];
for (let year = new Date().getFullYear(); year !== null;) {
const row = [];
for (let i = 0; i < 5; i++, year = (year > 1901 ? year - 1 : null)) {
row.push(year);
}
theDates.push(row);
}
console.log(theDates);
Example of year other than 2020:
const theDates = [];
for (let year = 2023; year !== null;) {
const row = [];
for (let i = 0; i < 5; i++, year = (year > 1901 ? year - 1 : null)) {
row.push(year);
}
theDates.push(row);
}
console.log(theDates);
I haven't tested it, but according to google you can do something like
var today = new Date();
var year = today.getFullYear();
since getFullYear() – Provides current year.

Trying to get Month and year range using Moment

I am trying to calculate Month name and year using moment for a range.
for example if the start year and month is 2016-02, and end year is 2017-11,
I want Moment to create date in
Feb-16 , Mar-16 ..Jan-17, Nov-17
Can you provide some idea? This is what I ma trying to do:
const startYear = 2016;
const startMonth = 2;
const endYear = 2017;
const endMonth = 12;
var ind = startMonth;
var i=0;
while(i < 24){
if(ind == 13){
ind = 1;
startYear++;
}
header = moment(startYear + '-'+ ind, 'YYYY-M').format('MMM-YY');
i++;
ind++;
return header ;
}
The output should be like :
Feb-16 Mar-16 Apr-16 May-16......Jan-17....Nov-17
when momentjs a library, try to use the convenience methods that they have for date manipulation instead of just using it for parsing
var startDate = moment('2012-1');
var endDate = moment('2013-1');
var out = [startDate];
while (startDate.isBefore(endDate)) {
startDate = startDate.add(1, 'month');
out.push(startDate);
}

how can i count the range between 2 dates without counting the weekend in javascript

i want to calculate the range between 2 dates without counting weekend in javascript. i have some code that already count the range between them. but i'm stuck with the weekend part. date inputed by CJuiDatePicker in YII framework
<script>
function calcDay(dt1, dt2, range){
var msec1 = dt1;
var date1 = new date(msec1);
var msec2 = dt2;
var date2 = new date(msec2);
if(date1>0 || date2>0){
range.val(isFinite(Math.round(date2-date1)/86400000) || 0);
}
};
</script>
86400000 is day in millisecond
thanks in advance
The function you'll need is getUTCDay().
the pseudo code would be as follows:
1 - determine full weeks (days/7 truncated)
2 - calculate weekday/weekend: 2 * result = weekend days, 5 * result = weekdays.
3 - after that, remainder and starting day of week will determine the 1 or 2 additional days
Hope that helps, let me know if you need the javascript,
- John
Edited, as requested. NOTE: tweaked your original for testing, you should spot the needed changes to restore.
function calcDay(dt1, dt2, range)
{
var msec1 = "October 13, 2014 11:13:00";
var date1 = new Date(msec1);
var msec2 = "October 13, 2013 11:13:00";
var date2 = new Date(msec2);
var days;
var wdays;
var startday;
var nLeft;
// neither should be zero
if(date1>0 && date2>0) {
days = Math.round( Math.abs((date2-date1)/86400000) );
wdays = Math.round(days / 7) * 5;
nLeft = days % 7;
startday = (date1 > date2) ? date2.getUTCDay() : date1.getUTCDay();
if (startday < 2) {
wdays += Math.max(nLeft+startday-1,0);
} else if (startday == 6) {
wdays += Math.max(nLeft-2,0);
} else if (nLeft > (7-startday)) {
wdays += (nLeft-2)
} else {
wdays += Math.min(nLeft, 6-startday)
}
}
};
i found my own solution, but i forgot to share it. this is how i make it
function myUpdate(dt1, dt2,range){
var msec1 = dt1;
var date1 = new Date(msec1);
var msec2 = dt2;
var date2 = new Date(msec2);
var diff = (isFinite(Math.round (date2 - date1) / 86400000) && Math.round (date2 - date1) / 86400000 || 0);
var wEnd=0;
if(date1>0 || date2>0){
for(var i=0; i<=diff; i++){
if(date1.getDay() ==6 || date1.getDay()==0){
wEnd = wEnd + 1;
}
date1.setDate(date1.getDate() + 1);
}
}
range.val(Math.round((diff-wEnd)+1));
};
first u should count the different date, then the date1 will be check if it is sunday or saturday. then date1 will be added 1 till the value of date1 is equal to date2. if date1 is/are saturday or sunday, wEnd will gain 1. so u can substract diff with wEnd. hope this can help u guys

Javascript to return last 6 months and then use each month as a variable

Hopefully someone can help.
I have the following function to return the last 6 monthly names (I.E June, July, August etc), however, I cannot work out how I would then use each returned month name as separate variables.
I need this so I can feed each month name in to an sql query that populates a table for the last 6 months.
Any help much appreciated.
function getMonths()
{
var today = new Date();
var month = 1;
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 = 6;
var buffer = 10;
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;
}
return (menuMonths.reverse());
}
console.log (getMonths());
You can use Array.slice()
FIDDLE http://jsfiddle.net/BeNdErR/NF5Qm/1/
CODE
var monthArray = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
var currMonth = 3; // the current month index, from 1 to 12
var firstMonth = currMonth - 6;
if(firstMonth < 0){ //for example if currMonth is January - 0
var months = [];
months.push(monthArray.slice(12 - Math.abs(firstMonth), 12));
months.push(monthArray.slice(0, currMonth));
alert(months);
}else{
alert(monthArray.slice(firstMonth, currMonth))
}
As output, you still have an array, so you can pass it to the SQL Query as it is, for example (SQLite):
tx.executeSql("SELECT * FROM tablename WHERE month = ? OR month = ? month = ? OR month = ? month = ? OR month = ?;", [slicedMonthArray], successCB, errorCB);
Hope it helps
var months = getMonths();
for(var i=0, len=months.length; i<len; i++){
var currentMonth = months[i];
alert(currentMonth);
//do whatever you want here;
}

Categories

Resources