Google script add row with date only on certain dates - javascript

I am trying to make a Google Sheet that automatically adds new rows with a weekday date in the first columns, two days before the respective date (Mondays get added on Saturday, Tuesdays on Sunday, etc.). For this I have written the following function:
function addRowsWithDate() {
var ss = SpreadsheetApp.getActiveSheet();
var Today = new Date();
Today.setDate(Today.getDate()+0); // I am using this to experiment with different dates
var newDate = new Date();
var dayOfWeek = Today.getDay();
if (dayOfWeek<=3 || dayOfWeek==6){ // On Saturday through Wednesday
newDate.setDate(Today.getDate()+2);
ss.insertRowsBefore(1, 1); // Add new rows
ss.getRange(1, 1).setValue(newDate); // Set date to the day after tomorrow
}
}
This works as expected if I leave the +0 as it is, or comment out that line, but once I start changing that value to experiment with what will happen when I run this code on different dates I returns dates in other months. For example, offsetting today to +3 (as of 31 September) adds a row with 5 September. Now that I am typing this I see the issue is possibly with getDate() returning the day of the month instead of the week like I read here. Is that correct? And if so, is there another function that returns the day of the week in Google Sheets scripts?
EDIT: it seems to be some wrapping issue. When I set +3 it returns 5 September instead of 5 October and if I set -30 I get 3 October again.

Instead of creating a new Date() for newDate, define newDate as new Date(Today) and then add 2 days to it inside the if loop.
Solution:
function addRowsWithDate() {
var ss = SpreadsheetApp.getActiveSheet();
var Today = new Date();
Today.setDate(Today.getDate()+3); // I am using this to experiment with different dates
var newDate = new Date(Today);
var dayOfWeek = Today.getDay();
if (dayOfWeek<=3 || dayOfWeek==6){ // On Saturday through Wednesday
newDate.setDate(newDate.getDate()+2);
ss.insertRowsBefore(1, 1); // Add new rows
ss.getRange(1, 1).setValue(newDate); // Set date to the day after tomorrow
ss.getRange(1, 2).setValue(Today);
}
}

Related

How to change current date -7 days from now - [PersianDatepicker]

I am using Babakhani Datepicker and actually i have done substract thing from datepicker but it does not work on this , so i want to cast -7 days from currentdate
I have done it on console Like this
var nowDate = new Date();
var days = 7;
nowDate.setDate(nowDate.getDate() - days);
var mamat = nowDate.toISOString().split('T')[0];
console.log(mamat);
but as i am using PERSIAN not GREGORIAN i cant convert it
I have to use it on this
$(".persianDate").pDatepicker();
today date is 1/13/2019
and i want it to be 1/7/2019
Babakhani Source :
http://babakhani.github.io/PersianWebToolkit/doc/datepicker/options/
let date = new Date();
date.setDate(date.getDate()-1);
console.log(date.toLocaleDateString());
// Woud log:
// 1/12/2019
console.log(date.toLocaleDateString('fa-IR'));
// Woud log:
// ۱۳۹۷/۱۰/۲۲
If you want to set the calendar, then you can pass the desired calendar as an argument to the toLocaleDateString method, as per the MDN docs. For example, passing 'ar-EG' will result in Arabic digits.
Possible duplicate of Subtract days from a date in JavaScript.

Get the date between 2 dates using node.js

In node.js I need to get the date within the date range of particular gap.
Consider two dates:
startDate:2016-07-10T00:00:00.000Z,
payByDate:"13"(13th of every month);
endDate:2016-10-08T00:00:00.000Z
I need an array of dates of monthly or weekly gap between these 2 dates.
My result Should be:(Monthly gap)
[2016-07-13T00:00:00.000Z,
2016-08-13T00:00:00.000Z,
2016-09-13T00:00:00.000Z]
EDIT:
My startdate is 2016-07-10T00:00:00.000Z , so i can calculate the noOfmonths using endDate-startdate, but the array entry should be by payByDate.
I am using MOMENT.JS, but its returning only noOfMonths not the dates. Please share your ideas. Thanks in advance.
Now is it possible to calculate the calculate the Above array.Please note that "payByDate" is string.
you can use getMonth() function to get the month of your date. then keep adding one to it till you reach the end date.
var arrayDates = [];
arrayDates.push(startDate);
var tempDate = new Date(new Date(startDate).setMonth(startDate.getMonth()+1));
while(tempDate < endDate)
{
arrayDates.push(tempDate);
var tempDate = new Date(new Date(tempDate).setMonth(tempDate.getMonth()+1));
}
Abouve logic will work for monthly gap. to get array of weekly gap, use getDate() function and keep adding 7 to it till you reach the end Date
Try using the manipulate method in moment.js to add a month to the starting date until you reach the second date.
Consider this code. Assuming that the first date and the last date are already moments when they are passed into this function, you can use the diff and manipulate methods to create an array of dates by month in between the two different dates:
EDIT:
function monthsBetween(payByDate, startDate, lastDate) {
var months = [];
//finds nearest date to the start date that is on the payByDate
var currentDate = startDate.date(parseInt(payByDate));
//checks if the date is after the startDate and adds a month if it is
if(!currentDate.isSameOrAfter(startDate)){
currentDate = currentDate.add(1, 'months');
}
while (currentDate.isSameOrBefore(lastDate)) {
months.push(currentDate);
currentDate = currentDate.add(1, 'months');
}
return months;
}

Javascript add days to a existing calendar object off by one month

I'm trying to read a date from a Calendar object and add a specific amount of days to it (i.e. 7)
Here is the code that I have:
var daysFromBeginDate = parseInt($("#policyDuration").val()) * 7
alert(daysFromBeginDate)
var beginDate = new Date("2015-04-24");
alert(beginDate)
var endDate = new Date("2015-05-08");
alert(beginDate.getDate() + daysFromBeginDate)
endDate.setDate(new Date(beginDate.getDate() + daysFromBeginDate));
alert(endDate.toString())
and I am getting Sun May 31 2015 17:00:000 GMT as my answer. It should be that with one less month, where is the extra month getting added?
JavaScript using the below call, I found out that the month argument counts starting from zero.
new Date(2015, 3, 1); // that's the 1st April 2015!
And what is causing the issue is the below code snippet in your code:-
endDate.getMonth() + 1
That is possibly the reason for your issue..
EDIT:
if the below code
var endDate = new Date("2015-05-08");
is changed to
var endDate = new Date();
you will get correct output..
it is because setDate sets the day of the month and April has only 30 days so it is rolled over and you get it as May and you get 31 because 24+7 is 31..

JS time calculation - How many times a date has occurred between two dates

I really need some assistance with a time calculation in JS.
Put basically I need to calculate how many times a day of a month has occurred between two dates.
For Example -
A date of 15th of the month between 1st February 2014 to 14 May 2014 would be 3
A date of 15th of the month between 1st February 2014 to 16 May 2014 would be 4
I've looked at moment Jquery library but it estimates that a month is 30 days so I wouldn't be exact and take into consideration leap years - months with 28 days etc..
It really needs to be exact because its for a chargeable event calculation. The dates can spare many years so could lead to in-accuries because of the 30 day thing.
Any help would be appreciated
There are probably a million ways to do this... here's a brute force way:
// add a "addDays() method to Date"
Date.prototype.addDays = function(days)
{
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
}
// provide two dates and a day ordinal you want to count between the two
function numOrdinalsBetweenDts(Date1, Date2, theOrdinal) {
var temp;
if(Date2 < Date1) { // put dates in the right order (lesser first)
temp = Date1;
Date1 = Date2;
Date2 = temp;
}
var workDate = Date1;
var ctr = 0;
while(workDate < Date2) { // iterate through the calendar until we're past the end
if(workDate.getDate() == theOrdinal) // if we match the ordinal, count it
ctr++;
workDate = workDate.addDays(1); // move the calendar forward a day
}
return ctr;
}
var result = numOrdinalsBetweenDts(new Date("July 21, 1901"), new Date("July 21, 2014"), 2);
console.log(result);
alert(result);
There is a slightly counter-intuitive behavior in the Javascript Date constructor where if you create a new Date with the day set to 0, it will assume the last day of the month. You can the use the following function get the number of days in a month:
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
The Javascript date object is leap-year aware, so you can use this function reliably.
You then just need to count the number of months between the start and end date and check each one to make sure the day number is actually present in the month. You can short-circuit this check if the day is less than or equal to 28.

Does this code work fine? I'd like to get the timestamp of the following date

I'm building a chrome extension now.
I'd like to set an alarm to be fired at 23:59:59 everyday, so I can reset some saved settings at the end of day.
I wrote this code below but, I'm not used to using Date Object.
And I'm worried if this code works fine and don't mess up everything.
Especially, I'm worried about the code for setting up an alarm again for the next day.
var day = now.getDate() + 1;
To get the date of the following day, I just add 1 to the returned value of "now.getDate()".
But, I wonder if the returned value of "now.getDate()" is the end of the month and because of that, adding 1 ends up getting the date which doesn't exist.
Please take a look at my code and tell me if this works fine or not.
Thank you in advance!!
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate();
var timestamp = Number(new Date(year, month, day, 23, 59, 59, 0));
//set an alarm for today at 23:59:59.
chrome.alarms.create('resetSpentTime', {
when: timestamp
});
// when alarm fires, do the following.
chrome.alarms.onAlarm.addListener(function() {
//clear some saved settings at the end of day.
//After that, set an alarm again for tomorrow at 23:59:59.
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate() + 1;
var timestamp = Number(new Date(year, month, day, 23, 59, 59, 0));
//set an alarm for tomorrow at 23:59:59.
chrome.alarms.create('resetSpentTime', {
when: timestamp
});
})
I'll suggest use date.js Link for date.js filefor all date operations in Javascript in which you can add days or parse dates easily. See the demo on given site.
You can try this. Nextday as well as end of month is auto handeled.
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
Source: Add days to JavaScript Date

Categories

Resources