Javascript loop through months and years - javascript

I'm wondering how to create single loop for create variable between today and start date.
var startDate = 11-15; /*that means 11th month of 2015*/
var d = new Date();
var m = d.getMonth() + 1;
var y = d.getFullYear().toString().substr(-2);
for (var i = 11; i <= m; i++) {
console.log(i);
}
Result should be 11-15, 12-15, 1-16 and so on until today 9-17. I don't know how I can add year into my code.

Assuming startdate is a string you can use below code
var startDate = "11-15"
var d = new Date();
var m = d.getMonth() + 1;
var y = d.getFullYear().toString().substr(-2);
d=startDate.split("-")
counter = parseInt(d[0])
for(var i=parseInt(d[1]);i<=parseInt(y);i++)
{
for(var j=counter;j<=12;j++){
if(j>m && i==y){
continue
}
console.log(j+"-"+i)
}
counter = 1;
}

Well you can use .split() over startDate which should be a string, and extract month and year and keep incrementing them respectively until you reach 09-17:
var startDate = "11-15";
var month = parseInt(startDate.split("-")[0]);
var year = parseInt(startDate.split("-")[1]);
var results = [];
while(!(year === 17 && month === 9)){
if(month<12){
month++;
}else{
month = 1;
year++;
}
console.log(month+'-'+year);
results.push(month+'-'+year);
}
console.log(results);

Related

create array of array of datepairs that have gap of n days between them

Consider 2 dates, format will be MM/DD/YYYY
1st date = today
2nd date = 45 days from today
Note: Here, the 1st date and 2nd date are variable.
i.e. 1st date that is today can be tomorrow or any other date. 2nd date can be 15 days, 24 days, 105 days i.e. this "n" can also vary.
Assuming the above 2 dates as startDate and stopDate. I want to create array of datePairs of a given gap between them.
For e.g. if startDate = 12/01/2022 & stopDate = 12/20/2022. I want to have datePairs having gap of 2 (n = 2) days between them. So, the output array should look like
[
['12/01/2022', '12/03/2022'],
['12/04/2022', '12/06/2022'],
['12/07/2022', '12/09/2022'],
['12/10/2022', '12/12/2022'],
['12/13/2022', '12/15/2022'],
['12/16/2022', '12/18/2022'],
['12/19/2022', '12/20/2022']
]
NOTE: Here, the last array does not have the gap of 2 dates because it's just 1 day away from the stopDate. In such case, the last pair can have less gap between them.
The only condition is the above array length should always be even.
Date.prototype.addDays = function (days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
function splitInto(array, size, inplace) {
var output, i, group;
if (inplace) {
output = array;
for (i = 0; i < array.length; i++) {
group = array.splice(i, size);
output.splice(i, 0, group);
}
} else {
output = [];
for (i = 0; i < array.length; i += size) {
output.push(array.slice(i, size + i));
}
}
return output;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
var i = 0;
while (currentDate <= stopDate) {
if (i % 2 == 1) {
const options = {
year: 'numeric'
};
options.month = options.day = '2-digit';
var formattedCSTDate = new Intl.DateTimeFormat([], options).format(currentDate);
dateArray.push(formattedCSTDate);
currentDate = currentDate.addDays(1);
} else {
const options = {
year: 'numeric'
};
options.month = options.day = '2-digit';
var formattedCSTDate = new Intl.DateTimeFormat([], options).format(currentDate);
dateArray.push(formattedCSTDate);
currentDate = currentDate.addDays(3);
}
i = i + 1;
}
return dateArray;
};
var dateArray = getDates(new Date(), (new Date()).addDays(43));
var datePairLength = 2;
var rangeArray = splitInto(dateArray, datePairLength, false);
console.log(rangeArray);
It seems to me you're making it more complicated than it needs to be. Just build each range as an array and avoid the splitInto function. You might use a date library (there are many to chose from) for adding days and formatting:
function makeRanges(start = new Date(), end = new Date(), interval = 1) {
let f = new Intl.DateTimeFormat('default', {
year:'numeric',month:'short',day:'2-digit'
});
let s = new Date(start);
let ranges = [];
while (s < end) {
let t = new Date(s);
t.setDate(t.getDate() + interval);
ranges.push([f.format(s), t < end? f.format(t) : f.format(end)]);
s.setDate(s.getDate() + interval + 1)
}
return ranges;
}
console.log(
makeRanges(new Date(2022,0,1), new Date(2022,1,1), 2)
);

How to get the last months and years from current date

I want to create the JSON formatted as shown below, in decreasing order starting from current date (it will be the actual current date).
var theMonths = [
{"date":"2015-12","value":null}, {"date":"2016-01","value":null},
{"date":"2016-02","value":null}, {"date":"2016-03","value":null},
{"date":"2016-04","value":null}, {"date":"2016-05","value":null},
{"date":"2016-06","value":null}, {"date":"2016-07","value":null},
{"date":"2016-08","value":null}, {"date":"2016-09","value":null},
{"date":"2016-10","value":null}, {"date":"2016-11","value":null},
{"date":"2016-12","value":null}, {"date":"2017-01","value":null},
{"date":"2017-02","value":null}, {"date":"2017-03","value":null},
{"date":"2017-04","value":null}, {"date":"2017-05","value":null}
]
I want to pass this data in a chart.
var dateFromPast = [];
var amountOfDatesFromPast = 18;
for (var i = 0; i < amountOfDatesFromPast; i++){
var dateObj = new Date();
dateObj.setMonth(dateObj.getMonth() - i);
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var year = dateObj.getUTCFullYear();
newdate = year + "-" + month;
dateFromPast.push(newdate);
}
console.log(dateFromPast);

Find when month appears five times in JavaScript loop (date, string)

I am building a paycheck month calculator. If you normally get paid every other week, most months will have two paychecks but two months of each year will have three paychecks.
My program works as expected, it appends to a list the date of everyday starting today (today being a Friday). Now I would like to make list items with the same month that appears five times stand out, simple coloring would work.
Can this be done with a second function for li in ul and then if li[i] string[4][6] === the next li[i][4][6] and then somehow search for five? I'm not sure how the logic would work. The reason why I picked [4][6] is because in each list item, the months are all three letter abbreviations that occupy the same part of the string.
How can this be done?
var d;
var week = 7;
function getDates() {
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
$('#date').append("<li>" + d + "</li>");
week += 7;
};
}
$(document).ready(function() {
getDates();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="date"></ul>
A dirty example:
var d;
var week = 7;
function getDates() {
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
$('#date').append("<li data-mth='"+d.getMonth()+"'>" + d + "</li>");
week += 7;
}
$('li[data-mth]').each(function(){
var $group = $('li[data-mth="'+ $(this).data("mth") +'"]');
if( $group.length > 4 ) $group.addClass("standOut");
});
}
$(getDates);
.standOut{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="date"></ul>
You could put dates in a array where the month is the key, then loop the months and if the count on that month == 5 colour all the dates.
var d;
var week = 7;
$(document).ready(function() {
getDates();
});
function getDates() {
var months = new Array;
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
var month = d.getMonth();
if(!months[month]) months[month] = new Array;
months[month].push(d);
week += 7;
};
plot_months(months);
}
function plot_months(months){
$.each(months,function(key,month){
var style = "";
if(month.length > 4) style = "color:red;";
$.each(month,function(week,date){
$('#date').append('<li style="'+style+'">' +date+ "</li>");
});
});
}`
See this fiddle

get an array of dates for the past week in format dd_mm

I need to have an array of dates for whole days of the last week, including the current day, for e.g
['05/06', '04/06', '03/06', '02/06', '01/06', '31/05', '30/05']
(format dd/mm)
how can i do this?
I know there is the Date() object, but other than that I'm stumped.
logic along the lines of:
var dates = [];
var today = new Date();
for (var i = 0; i<7; i++){
var date = today - (i+1);
dates.push(date);
}
So you want an array containing todays date and a further 6 elements, with todays date-1, todays date-2 etc...?
var dates = [];
var date = new Date();
for (var i = 0; i < 7; i++){
var tempDate = new Date();
tempDate.setDate(date.getDate()-i);
var str = tempDate.getDate() + "/" + tempDate.getMonth();
dates.push(str);
}
console.log(dates);
Output: ["5/5", "4/5", "3/5", "2/5", "1/5", "31/4", "30/4"]
If you need numbers with leading 0's, try this:
var dates = [];
var date = new Date();
for (var i = 0; i < 7; i++){
var tempDate = new Date();
tempDate.setDate(date.getDate()-i);
var str = pad(tempDate.getDate()) + "/" + pad(tempDate.getMonth());
dates.push(str);
}
console.log(dates);
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Output: ["05/05", "04/05", "03/05", "02/05", "01/05", "31/04", "30/04"]
Check this working sample, where all days are printed out:
http://jsfiddle.net/danyu/Tu5R6/6/
This is the main logic:
for(var i=7;i>0;i--)
{
tempDate.setDate(tempDate.getDate()-1);
output+=tempDate+"<br/>";
}
Modify it to store those days into your array.

date error for date class google appscript

The problem that i am having here is that when i minus back to then end of the month, instead of going back to the 29 or 28 of last month the program starts to minus months instead of days. Bellow is my full code and below that is the output it produces in the google spread sheet.
function trying(){
var date = new Date();
var datechange = new Date();
var array = new Array(7);
for (var i = 0; i < 7; i++) {
array[i] = new Array(0);
}
for ( var i = 0; i < 7; i++){
days = i + 8
datechange.setDate(date.getDate() - days);
var tabName = Utilities.formatDate(datechange, 'MST', 'yyyy-MM-dd').toString();
array[i][0] = tabName;
}
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Want");
sheet.getRange("B2:B8").setValues(array);
}
This are the dates that are produced.
05/07/2012
04/07/2012
03/07/2012
02/07/2012
01/07/2012
30/06/2012
30/05/2012
You have to define datechange inside your loop, and not outside:
var date = new Date();
for ( var i = 0; i < 30; i++){
days = i + 8
var datechange = new Date();
datechange.setDate(date.getDate() - i);
console.log(datechange);
}
Date.getDate() returns the date (1-31) - so what you are doing is not correct.
Instead try this:
var ONE_DAY = 24 * 60 * 60 * 1000; //in milliseconds
for ( var i = 0; i < 7; i++){
days = i + 8
datechange.setDate(date.getTime() - (days * ONE_DAY));
var tabName = Utilities.formatDate(datechange, 'MST', 'yyyy-MM-dd').toString();
array[i][0] = tabName;
}
This is how JavaScript dates work. See here for full details.

Categories