Javascript - Adding Days to a Loop - javascript

I have the following
var my_date = '2021-09-27';
my_date = new Date(my_date);
var new_date = new Date();
for(var i=0; i<10; i++)
{
new_date.setDate(my_date.getDate() + i);
var this_date = new_date.toISOString();
console.log(this_date);
}
I was expecting it to output
2021-09-27T19:21:26.361Z
2021-09-28T19:21:26.361Z
2021-09-29T19:21:26.361Z
2021-09-30T19:21:26.361Z
2021-10-01T19:21:26.361Z
2021-10-02T19:21:26.361Z
2021-10-03T19:21:26.361Z
2021-10-04T19:21:26.361Z
2021-10-05T19:21:26.361Z
2021-10-06T19:21:26.361Z
but for some reason it outputs
2021-10-27T19:21:26.361Z
2021-10-28T19:21:26.361Z
2021-10-29T19:21:26.361Z
2021-10-30T19:21:26.361Z
2021-10-31T19:21:26.361Z
2021-11-01T19:21:26.361Z
2021-12-03T19:21:26.361Z
2022-01-03T19:21:26.361Z
2022-02-04T19:21:26.361Z
2022-03-08T19:21:26.361Z
As you can see it starts in October not September, and then when it hits the 31st it starts to jump months.
Why is this script behaving like this?
All the examples I have found online seem to suggest this would work.
Thanks

Because setDate only changes days, so when you create new Date() it has current month in it. You have to copy original date to make this works properly.
Here's the fix:
var my_date = '2021-09-27';
my_date = new Date(my_date);
for(var i=0; i<10; i++)
{
// clone date
var new_date = new Date(my_date.getTime())
new_date.setDate(my_date.getDate() + i);
var this_date = new_date.toISOString();
console.log(this_date);
}

Related

Get previous and next weeks from a calendar using JavaScript

I want to make a week planner, that displays all days of the week and the according date to it. And of course the month.
(Unfortunately, I don't have enough reputation to post a screenshot of what my calendar looks like.)
My JavaScript code looks like this. I found a part of it from Stack Overflow.
function calendar() {
var today = new Date();
var currYear = today.getFullYear();
var currMonth = today.getMonth();
var currWeek = today.getWeek()-1;
var firstDateOfMonth = new Date(currYear, currMonth, 1);
var firstDayOfMonth = firstDateOfMonth.getDay();
var firstDateOfWeek = new Date(firstDateOfMonth);
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() +
(firstDayOfMonth ? 7 - firstDayOfMonth : 0)
);
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() +
7 * (currWeek-1)
);
var dateNumbersOfMonthOnWeek = [];
var datesOfMonthOnWeek = [];
for (var i = 0; i < 7; i++) {
dateNumbersOfMonthOnWeek.push(
firstDateOfWeek.getDate());
datesOfMonthOnWeek.push(
new Date(+firstDateOfWeek));
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() + 1);
}
setText('month-year', monthArray[currMonth] + " " + currYear);
setText('Mo', dateNumbersOfMonthOnWeek[0]);
setText('Di', dateNumbersOfMonthOnWeek[1]);
setText('Mi', dateNumbersOfMonthOnWeek[2]);
setText('Do', dateNumbersOfMonthOnWeek[3]);
setText('Fr', dateNumbersOfMonthOnWeek[4]);
setText('Sa', dateNumbersOfMonthOnWeek[5]);
setText('So', dateNumbersOfMonthOnWeek[6]);
};
function setText(id, val) {
if(val < 10){
val = '0' + val;
}
document.getElementById(id).innerHTML = val;
};
window.onload = calendar;
It works as it displays the correct days for the weekdays (so, 08 for this Monday, 09 for this Tuesdays, etc) and also the month is the correct one.
The question now is how to get the previous or next week? When I click on the "<" arrow I want to see the previous week. So how should I write the loop, which parameters does the method need, etc. I am very thankful for every hint, link, example etc.
For next week-
var today = new Date();
var nextweek = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7);
for more detail check following link:-
how to get next week date in javascript

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.

Javascript getMonth() and getDate transions issuse

Hello i am trying to write the following function to display 7 days of the week
function displaydates(){
// read the string output from the datepicker and
//evalutes which date goes into which cell
var date = document.getElementById("datepicker"); // Mon APR 30 2012 HH:MM:SS
var m = new Date(date.value);
var num = parseInt(m.getDate());
var i = 0;
var days=[];
var x;
for(i; i<=6; i++){
var day= m.setDate(num+i);
var month = m.setMonth(m.getMonth());
x = m.getMonth()+1 + "/" + m.getDate() + "<br />";
days.push(x);
}
document.getElementById("Monday").innerHTML= days[0];
document.getElementById("Tuesday").innerHTML=days[1];
document.getElementById("Wednesday").innerHTML=days[2];
document.getElementById("Thursday").innerHTML=days[3];
document.getElementById("Friday").innerHTML=days[4];
document.getElementById("Saturday").innerHTML=days[5];
document.getElementById("Sunday").innerHTML=days[6];
}
the code works fine as long as it's seven days before the next month.the problem i am having is when the user wants to see the next seven day the function outputs the wrong information
for example
var m = new Date("Apr 30 2012"); / /monday
will make my function out put the following
4/29, 5/30, 7/1, 9/1, 11/2, 1/3, 3/7
again, this only happens on transition to the next month is there and thing i can do to make the month to month transition work in my function
When you call, for example, setDate(32), JavaScript figures out that that requires an additional month and adds it to the date. When you later call setDate(33), it once again adds an extra month...
This solution might work better (some parts are omitted):
var start = new Date();
var days = [];
for(var i = 0; i <= 6; ++i) {
var str = (start.getMonth() + 1) + '/' + start.getDate() + '<br />';
days.push(str);
start.setDate(start.getDate() + 1);
}
Please use the below provided solution
function displaydates(){
// read the string output from the datepicker and
//evalutes which date goes into which cell
var date = document.getElementById("datepicker"); // Mon APR 30 2012 HH:MM:SS
var m = new Date(date.value);
var num = m.getTime();
var i = 0;
var days=[];
var x;
for(i; i<=6; i++){
num+=86400000; //Edited Part
m = new Date(num);
var day= m.getDate();
var month = m.getMonth();
x = month+1 + "/" + day + "<br />";
days.push(x);
}
document.getElementById("Monday").innerHTML= days[0];
document.getElementById("Tuesday").innerHTML=days[1];
document.getElementById("Wednesday").innerHTML=days[2];
document.getElementById("Thursday").innerHTML=days[3];
document.getElementById("Friday").innerHTML=days[4];
document.getElementById("Saturday").innerHTML=days[5];
document.getElementById("Sunday").innerHTML=days[6];
}
Hope this solves your problem.

How to convert a string to a 24hr time?

So I have a JSON returning times like "10:00am"> i need to create an array with eight other times from the current system time. so it would go like "10:00am, 11:00am, 12:00pm, 1:00am, etc"
Here's my current code so far:
var katie=new Array();
var webdate = new Date().getHours();
var firsthr = day.date.start.time;
for (i=0; i<=8; i++){
katie{i] = webdate;
webdate = webdate +1;
}
You can try like this .
var str=new Array();
var webdate = new Date();
for (i=0; i<=8; i++){
webdate.setHours(i);
str[i] = webdate;
}
Date.js is a very helpful library for parsing strings into dates.
On this api doc page for Date.js search for ".parse". Also, the FormatSpecifiers page is helpful for converting dates to a string.
You said you have a JSON with the string, "10:00am". Assuming this JSON,
var data = {time: "10:00am"};
You could create a date object like this:
var date = Date.parse(data.time);
// this will create a date object with today's date and time set to 10am
Then, you can use your loop to increment the time to hours past 10am. Altogether it could look like this
<script src="date.js"></script>
<script>
var data = {time: "10:00am"};
var date = Date.parse(data.time);
//push today # 10am
var katie=new Array(new Date(date));
for (i=0; i<=8; i++){
//add an hour to date, then push new Date object based on date
date.add({hours:1});
katie.push(new Date(date));
}
</script>
You could try this -
var str=new Array();
var webdate = new Date();
var currenthours = webdate.getHours();
var looplimit = currenthours + 8;
for (i=currenthours; i<looplimit; i++){
webdate.setHours(i);
str[i] = webdate.getHours() >= 12 ? webdate.getHours() -12 +':00pm' : webdate.getHours() +':00am';
}
}

Categories