Returning Dates In A Formatted Format (Iteration) - google-apps-script

I am trying to create tabs with each tab name being the date of the start of each week in the year. So, "Jan 01" then "Jan 08" then "Jan 14" etc.
Essentially, taking x date then adding +7 days and returning that value as a date 7 days from x date.
function CreateWeekTabs(){
var TotalsSheet = spreadsheet.getSheetByName("Totals");
var StartingWeek = new Date(TotalsSheet.getRange("B1").getValue()); //Typically always "Jan 01" shwon. Cell Formatting is MMM DD. Cell Value is 01/01/2019
var CurrentWeek = new Date();
var NextWeek = new Date();
spreadsheet.toast("Please wait...","Creating Tabs");
for (var WeekNum = 1;WeekNum <= 2;WeekNum++){
var DayIncrease = 7 - (7 * WeekNum); //Should produce 0,7,14,21,28.... So first iteration won't increase any value from Jan 01.
CurrentWeek.setDate(StartingWeek.getDate()+DayIncrease); //E.g. First Iteration = Jan 01 + 0 = Jan 01; Second Iteration = Jan 01 + 7 = Jan 08;
NextWeek.setDate(CurrentWeek.getDate()+7); //Should be +7 days from CurrentWeek Value.
var WeekSheetName = Utilities.formatDate(NextWeek,spreadsheet.getSpreadsheetTimeZone(),"MMM DD"); //Should return the date formatted.
Logger.log(WeekNum+" - "+WeekSheetName);
}
}
With Each Iteration, I intend to create WorkSheets with the First Date of each Week Starting from Value of CurrentWeek
Eg: Jan 01, Jan 08, Jan 15, Jan 22, Jan 29, Feb 05, etc...
UPDATE:
I since changed the code to:
function CreateWeekTabs(){
var TotalsSheet = spreadsheet.getSheetByName("Totals");
var CurrentWeek = new Date(TotalsSheet.getRange("B1").getValue()); //Typically always "Jan 01" shown. Cell Formatting is MMM dd. Cell Value is 01/01/2019
// var CurrentWeek = new Date();
var NextWeek = new Date();
spreadsheet.toast("Please wait...","Creating Tabs");
for (var WeekNum = 1;WeekNum <= 12;WeekNum++){
var DayIncrease = (7 * WeekNum) - 7; //Should produce 0,7,14,21,28.... So first iteration won't increase any value from Jan 01.
CurrentWeek.setDate(CurrentWeek.getDate()+DayIncrease); //E.g. First Iteration = Jan 01 + 0 = Jan 01; Second Iteration = Jan 01 + 7 = Jan 08;
NextWeek.setDate(CurrentWeek.getDate()+DayIncrease+7); //Should be +7 days from CurrentWeek Value.
var WeekSheetName = Utilities.formatDate(NextWeek,spreadsheet.getSpreadsheetTimeZone(),"MMM dd"); //Should return the date formatted.
Logger.log("Week Number: "+WeekNum+" - Current Week: "+Utilities.formatDate(CurrentWeek,spreadsheet.getSpreadsheetTimeZone(),"MMM dd")+" Next Week: "+WeekSheetName);
}
}
and the Log is producing the following as outputs. (so I can see what it's producing for Variables 'CurrentWeek' and 'NextWeek'
[19-06-14 14:40:00:463 EDT] Week Number: 1 - Current Week: Jan 01 Next Week: Jun 08
[19-06-14 14:40:00:464 EDT] Week Number: 2 - Current Week: Jan 08 Next Week: Jun 22
[19-06-14 14:40:00:464 EDT] Week Number: 3 - Current Week: Jan 22 Next Week: Jul 13
[19-06-14 14:40:00:465 EDT] Week Number: 4 - Current Week: Feb 12 Next Week: Aug 09
[19-06-14 14:40:00:466 EDT] Week Number: 5 - Current Week: Mar 12 Next Week: Sep 16
[19-06-14 14:40:00:467 EDT] Week Number: 6 - Current Week: Apr 16 Next Week: Oct 28
[19-06-14 14:40:00:468 EDT] Week Number: 7 - Current Week: May 28 Next Week: Dec 16
[19-06-14 14:40:00:468 EDT] Week Number: 8 - Current Week: Jul 16 Next Week: Feb 10
[19-06-14 14:40:00:469 EDT] Week Number: 9 - Current Week: Sep 10 Next Week: Apr 13
[19-06-14 14:40:00:470 EDT] Week Number: 10 - Current Week: Nov 12 Next Week: Jun 21
[19-06-14 14:40:00:471 EDT] Week Number: 11 - Current Week: Jan 21 Next Week: Sep 06
[19-06-14 14:40:00:471 EDT] Week Number: 12 - Current Week: Apr 07 Next Week: Nov 30
Why the blazes? Current Value is calculating correctly, but the value of Next Week is way off, it should be showing +7 days from Current Week.

Try these:
The first calculates the start of week tab name for this week. You can pick the start of week day Sun-Sat is 0-6. The second calculates the start of week tab name for next week.
function thisWeeksStartOfWeekTabname(sow){
var sow=sow || 1;//Sun-0, Sat=6
var ss=SpreadsheetApp.getActive();
var dt=new Date();
while(dt.getDay()>0) {
dt=new Date(dt.setDate(dt.getDate()-1));
}
dt=new Date(dt.setDate(dt.getDate()+sow));
Logger.log(Utilities.formatDate(dt, Session.getScriptTimeZone(), "MMM dd"));
return Utilities.formatDate(dt, Session.getScriptTimeZone(), "MMM dd");
}
function nextWeeksStartOfWeekTabname(sow){
var sow=sow || 1;//Sun-0, Sat=6
var ss=SpreadsheetApp.getActive();
var dt=new Date();
while(dt.getDay()>0) {
dt=new Date(dt.setDate(dt.getDate()+1));
}
dt=new Date(dt.setDate(dt.getDate()+sow));
Logger.log(Utilities.formatDate(dt, Session.getScriptTimeZone(), "MMM dd"));
return Utilities.formatDate(dt, Session.getScriptTimeZone(), "MMM dd");
}

Related

Google Apps Script; how to solve TypeError: Cannot read properties of undefined (reading '0')?

I have a Google sheet which I follow stock prices Daily; every day I get the stock prices online and write them to the sheet via apps script. Now I want to check monthly P/L for each stock and create a sheet that shows monthly P/L for each stock.
I am trying to get the prices with dates for each stock in an array and then push the first and last entries for every month in "monthly" array. And then I am trying to write this monthly values in "Aylık P/L" sheet.
The code works fine till I added "for" statement to write the monthly datas to the sheet; it throws: "Error in Monthly: TypeError: Cannot read properties of undefined (reading '0')":
Here goes the code:
function aylikRapor() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Fiyat Çek');
var sheet2 = ss.getSheetByName('Günlük Fon Takip');
var sheet3 = ss.getSheetByName('Haftalık Fon Takip');
var sheet4 = ss.getSheetByName('Aylık Fon Takip');
var sheet5 = ss.getSheetByName('Funds Main');
var sheet6 = ss.getSheetByName('Aylık');
var sheet7 = ss.getSheetByName('Aylık P/L');
var pfs = sheet5.getRange(1,1).getValue(); // pfs = PortföydekiFonSayısı
var i = 1;
var f = 1;
var a;
var b;
try {
for(i=1; i<=pfs; i++) {
var colH = sheet2.getRange(1,3*i,1,1);
var harf = colH.getA1Notation().match(/([A-Z]+)/)[0];
var column = sheet2.getRange(harf+":"+harf);
// get lastFilledRow
var value = ''
const max = sheet2.getMaxRows()
var values = column.getValues()
values = [].concat.apply([], values)
for (row = max - 1; row > 0; row--) {
value = values[row]
if (value != '') { break }
}
lastRowD = row + 1;
Logger.log(lastRowD);
let veriler = sheet2.getRange(14,3*i-1,lastRowD-12,2).getValues();
let month = veriler[0][0].getMonth();
let monthly = [[veriler[0][0],veriler[0][1]]];
veriler.forEach( (row,index) => {
let test = new Date(row[0]).getMonth();
if( test !== month ) {
monthly.push([veriler[index-1][0],veriler[index-1][1]]);
monthly.push([row[0],row[1]]);
month = test;
}
}
)
Logger.log(monthly);
for (f=1, a=0, b=1; f <=monthly.length-1; f++, a+=2, b+=2){
sheet7.getRange(3+f,5*i-2).setValue(monthly[a][0]);
sheet7.getRange(3+f,5*i-1).setValue(monthly[a][1]);
sheet7.getRange(3+f,5*i).setValue(monthly[b][0]);
sheet7.getRange(3+f,5*i+1).setValue(monthly[b][1]);
}
}
}
catch(err) {
Logger.log("Error in Monthly: "+err);
}
}
I think there is a null value in "monthly" array; but I could not figure out how I can solve it!
Execution Log:
Yürütme günlüğü
09:49:37 Bildirim Yürütme işlemi başlatıldı
09:49:49 Bilgi 119.0
09:49:50 Bilgi [[Wed Aug 17 00:00:00 GMT+03:00 2022, 0.080777], [Wed Aug 31 00:00:00 GMT+03:00 2022, 0.082585], [Thu Sep 01 00:00:00 GMT+03:00 2022, 0.0831], [Fri Sep 30 00:00:00 GMT+03:00 2022, 0.08431], [Mon Oct 03 00:00:00 GMT+03:00 2022, 0.085019], [Mon Oct 31 00:00:00 GMT+03:00 2022, 0.096867], [Tue Nov 01 00:00:00 GMT+03:00 2022, 0.098144], [Wed Nov 30 00:00:00 GMT+03:00 2022, 0.115665], [Thu Dec 01 00:00:00 GMT+03:00 2022, 0.117343], [Fri Dec 30 00:00:00 GMT+03:00 2022, 0.126554], [Mon Jan 02 00:00:00 GMT+03:00 2023, 0.127234], [Thu Jan 12 00:00:00 GMT+03:00 2023, 0.111894], [, ]]
09:49:50 Bilgi Error in Monthly: TypeError: Cannot read properties of undefined (reading '0')
09:49:38 Bildirim Yürütme işlemi tamamlandı
I have fixed the problem:
As you can see from the execution log; for i=1 the first monthly array length is 12; during the for (f=1, a=0, b=1; f <=monthly.length-1; f++, a+=2, b+=2)
the max f should be 6; so after 6 there would be no values in the array.
I fixed the problem by the following amendment:
(f=1, a=0, b=1; f <=monthly.length/2; f++, a+=2, b+=2)
I hope the others could get some help in case problems like this.

Set age group based on DOB

I would like to create a Google Sheet function that if supplied with a date of birth, looks up the below table and gives the appropriate age group. I will be using this table to group 200 kids for surf lifesaving.
for example...date of Birth is 11 Oct 2011, then the age group will be U7. I have use the query function to get this data but I would like to contain it in a function and store the table as a array and compare the date to the array table.
- U 5 01 Oct 2013 30 Sep 2017
- U 6 01 Oct 2012 30 Sep 2013
- U 7 01 Oct 2011 30 Sep 2012
- U 8 01 Oct 2010 30 Sep 2011
- U 9 01 Oct 2009 30 Sep 2010
- U 10 01 Oct 2008 30 Sep 2009
- U 11 01 Oct 2007 30 Sep 2008
- U 12 01 Oct 2006 30 Sep 2007
- U 13 01 Oct 2005 30 Sep 2006
- U 14 01 Oct 2004 30 Sep 2005
Dates can be a little tricky. See This question to get a better idea. But this script can at least get you started.
This Google Sheet demonstrates a custom formula (AGEGROUP) to compare the input date to a "age-groups" sheet.
Note: Only add to "age-groups" sheet if needed.
The last row with a value is used to consider if someone is too old.
The first row of the sheet is used to see if someone is too young.
AGEGROUP() will accept a cell reference to look up
Example AGEGROUP(B2)would check cell B2, assuming it contains a date, and return a group assignment (U 5, U 6, U7...).
Looking up dates manually (instead of referencing another cell) can be accomplished by nesting DATE inside of AGEGROUP. You must follow the right arguments for DATE (year, month, day).
Example AGEGROUP(DATE(2010,1,21))
I'm new to custom functions and did not look into the options for supporting function details like #param or #return and so on.
Apps Script
/**
* Finds age group of the input value (date).
*
* #param {date} Input the date to compare to date ranges.
* #return Returns age groupd based on provided date.
* #customfunction
*/
function AGEGROUP(date) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var ages = ss.getSheetByName("age-groups");
var range = ages.getDataRange();
var values = range.getValues();
var i = 0;
var ranges = values.length;
var lastRow = ranges -1;
// loop through dateRanges
for(i; i < ranges; i++) {
// if date in AGEGROUP()
if(date >= values[i][1] && date <= values[i][2]) {
// return age group
return values[i][0];
}
// if child is too old
if(date > values[0][2]) {
return "Child is too young.";
}
// if child is too young
if(date < values[lastRow][1]) {
return "Child is too old.";
}
}
}

Utilities.formatDate - incorrect year in the formatted string [duplicate]

This question already has answers here:
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 5 years ago.
In Google App Script consider the following date formatting code
function testDateFormatter(){
// Sun Dec 31 2017 20:02:06
var date = new Date(1514746926811)
var dateString = Utilities.formatDate(date, "CET", "YYYY-MM-dd");
Logger.log("The date is : " + date + ", after formatting it is " + dateString)
}
The result is:
//
// The date is : Sun Dec 31 2017 20:02:06 GMT+0100 (CET), after formatting it is 2018-12-31
//
note 2018 instead of 2017 !!!!
Why GAS added the whole year to the date?
With other sample dates it works fine i.e.:
var date = new Date(1511377747255)
var dateString = Utilities.formatDate(date, "CET", "YYYY-MM-dd");
Logger.log("The date is : " + date + ", after formatting it is " + dateString)
//
// Logger: The date is : Wed Nov 22 2017 20:09:07 GMT+0100 (CET), after formatting it is 2017-11-22
//
I don't see the problem:
function myFunction() {
var dt=new Date(1514746926811);
var dts=Utilities.formatDate(dt, Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss")//not YYYY
Logger.log('dt=%s dts=%s',dt,dts);
}
Logger Output is:
[17-12-22 15:17:07:058 MST] dt=Sun Dec 31 12:02:06 GMT-07:00 2017 dts=12/31/2017 12:02:06

How to Display 4week per month with condition in sql

I have this logic but I cant figure out what to do to come up with the results. I want to achieve the results below, the idea is (Ex. month of October 2014), normally it has 5 weeks. If there is a 5th week and days is greater than 3 then consider whole week in the next month else add it to 4th week.
Input:
date range
from: 10-01-2014
to: 11-30-2014
Sample Output:
Date Customer week# Dates covered
10-01-2014 Cust01 1 Oct 01 - Oct 11, 2014
10-08-2014 Cust02 1 Oct 01 - Oct 11, 2014
10-17-2014 Cust02 2 Oct 12 - Oct 18, 2014
10-25-2014 Cust03 3 Oct 19 - Oct 25, 2014
10-31-2014 Cust01 4 Oct 26 - Oct 31, 2014
11-01-2014 Cust01 1 Nov 01 - Nov 08, 2014
11-28-2014 Cust02 4 Nov 23 - Nov 30, 2014
11-30-2014 Cust05 4 Nov 23 - Nov 30, 2014
Thanks
Use datepart(ww,[date]) to get week number in a year, then compare the week number by the begin date of a month.
Below is the detail approach to calculate for one date:
declare #dt date, #month_begin date, #month_end date, #week_of_month int
set #dt='20141031'
set #month_begin = convert(date,(convert(char(6),#dt,112)+'01'))
set #month_end = dateadd(day, -1, dateadd(month,1,#month_begin))
set #week_of_month = datepart(ww,#dt) - datepart(ww,convert(date,(convert(char(6),#dt,112)+'01'))) + 1
select
case when #week_of_month > 4 and datepart(dw,#month_end)>3
then 1
else #week_of_month
end as week,
case when #week_of_month > 4 and datepart(dw,#month_end)>3
then datepart(month,dateadd(month,1,#dt))
else datepart(month,#dt)
end as month

How to get start date and end date of current month in AS3

I have 2 DateFields named startDate and endDate I want to set startDate's Selected date to Current months start date and endDate's Selected date to Current months End date.
How can I achieve this?
Thanks in advance...
You mean this?
package
{
import flash.display.Sprite;
public class DateExample extends Sprite
{
public function DateExample()
{
super();
var now:Date = new Date();
trace("now: " + now.toString());
var startDate:Date = new Date(now.fullYear, now.month, 1);
trace("start: " + startDate.toString());
var endDate:Date = new Date(now.fullYear, ++now.month, 0);
trace("end: " + endDate.toString());
}
}
}
output:
now: Fri Oct 21 00:15:09 GMT-0500 2011
start: Sat Oct 1 00:00:00 GMT-0500 2011
end: Mon Oct 31 00:00:00 GMT-0500 2011