Setting week start/end dates in spreadsheet using apps script [duplicate] - google-apps-script

I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"
This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.
Making it work with first and last days in different months is left as an exercise for the user

Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.
You can use a third party date library to deal with dates. For example:
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)
Another popular alternative is date-fns.

You can also use following lines of code to get first and last date of the week:
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
Hope it will be useful..

The excellent (and immutable) date-fns library handles this most concisely:
const start = startOfWeek(date);
const end = endOfWeek(date);
Default start day of the week is Sunday (0), but it can be changed to Monday (1) like this:
const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});

Here's a quick way to get first and last day, for any start day.
knowing that:
1 day = 86,400,000 milliseconds.
JS dates values are in milliseconds
Recipe: figure out how many days you need to remove to get the your week's start day (multiply by 1 day's worth of milliseconds). All that is left after that is to add 6 days to get your end day.
var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000); //add 6 days to get last day

Small change to #Chris Lang answer.
if you want Monday as the first day use this.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
Thaks #Chris Lang

This works across year and month changes.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay())));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());

You could do something like this
var today = new Date();
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (7 - today.getDay() - startDay) % 7);
Where startDay is a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).

SetDate will sets the day of the month. Using setDate during start and end of the month,will result in wrong week
var curr = new Date("08-Jul-2014"); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)); // 06-Jul-2014
var lastday = new Date(curr.setDate(last)); //12-Jul-2014
If u setting Date is 01-Jul-2014, it will show firstday as 29-Jun-2014 and lastday as 05-Jun-2014 instead of 05-Jul-2014
So overcome this issue i used
var curr = new Date();
day = curr.getDay();
firstday = new Date(curr.getTime() - 60*60*24* day*1000); //will return firstday (ie sunday) of the week
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000); //adding (60*60*6*24*1000) means adding six days to the firstday which results in lastday (saturday) of the week

I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.
Simply to get current date time in specific format
case 'Today':
moment().format("DD/MM/YYYY h:mm A");
case 'This Week':
moment().endOf('isoweek').format("DD/MM/YYYY h:mm A");
Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.
case 'This Month':
moment().endOf('month').format("DD/MM/YYYY h:mm A");
case 'This Quarter':
moment().endOf('quarter').format("DD/MM/YYYY h:mm A");
I chose this format as per my need. You can change the format according to your requirement.

//get start of week; QT
function _getStartOfWeek (date){
var iDayOfWeek = date.getDay();
var iDifference = date.getDate() - iDayOfWeek + (iDayOfWeek === 0 ? -6:1);
return new Date(date.setDate(iDifference));
},
function _getEndOfWeek(date){
return new Date(date.setDate(date.getDate() + (7 - date.getDay()) === 7 ? 0 : (7 - date.getDay()) ));
},
*current date == 30.06.2016 and monday is the first day in week.
It also works for different months and years.
Tested with qunit suite:
QUnit.module("Planung: Start of week");
QUnit.test("Should return start of week based on current date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date());
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a sunday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-07-03"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a monday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-06-27"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.module("Planung: End of week");
QUnit.test("Should return end of week based on current date", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date());
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on sunday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-07-03"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on monday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-27"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 21-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-21"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 28-12-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-12-28"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-01-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-01-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});

var dt = new Date() //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));
This will be useful for any date scenario.

Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
function getFirstDayOfWeek(date, from) {
//Default start week from 'Sunday'. You can change it yourself.
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 7 : start);
d.setDate(diff);
return d;
};
Last day of week is just 6 days after first day of week
function getLastDayOfWeek(date, from) {
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
d.setDate(diff);
return d;
};
Test:
getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017

The biggest issue when the given date's week is in-between two months. (Like 2022-07-01, it's the 5th day of the week.)
Using getDay function we check if the week is in-between months.
Note: getDay() function identifies week start day as sunday, so it'll return 0 for sunday.
var curr = new Date(); // get current date
var weekdaynum = curr.getDay();
if(weekdaynum == 0){ //to change sunday to the last day of the week
weekdaynum = 6;
} else{
weekdaynum = weekdaynum-1;
}
var firstweek = curr.getDate() - weekdaynum;
var lastweek = firstweek + 6; // last day is the first day + 6
if((curr.getDate()-weekdaynum) <= 0){
var firstweek_lasmonth_lastdate = new Date(currweek.getFullYear(),currweek.getMonth(), 0);
var firstweek_diff = firstweek_lasmonth_lastdate.getDate()-Math.abs(firstweek);
var firstweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff);
var lastweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff+7);
} else{
var firstweekday = new Date(curr.setDate(firstweek));
var lastweekday = new Date(curr.setDate(lastweek));
}
So this will return (given date is: 2022/07/01):
firstweekday = Mon Jun 27 2022 00:00:00
lastweekday = Sun Jul 03 2022 00:00:00
Hope this helps.

krtek's method has some wrong,I tested this
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (6 - today.getDay() - startDay) % 7);
it works

Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016.
For this reason I think, the correct calculation should be like the below simply;
var d = new Date(),
dayInMs = 1000 * 60 * 60 * 24,
weekInMs = dayInMs * 7,
startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
todayElapsedTime = d.valueOf() - startOfToday,
dayDiff = d.getDay() * dayInMs,
dateDiff = dayDiff + todayElapsedTime,
// finally
startOfWeek = d.valueOf() - dateDiff,
endOfWeek = startOfWeek + weekInMs - 1;

JavaScript
function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
var cd = curr.getDate() - curr.getDay();
var from = new Date(curr.setDate(cd + firstDay));
var to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
TypeScript
export enum WEEK_DAYS {
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
export const getWeekDays = (
curr: Date,
firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
const cd = curr.getDate() - curr.getDay();
const from = new Date(curr.setDate(cd + firstDay));
const to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};

function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) ) // Mon Nov 08 2010

Pure vanilla JS. no third party libraries.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
^ this returns Sunday 00am to Sunday 00am. Adjust the "7" to get what you want.

var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 6)).toUTCString();
console.log("firstday", firstday);
console.log("lastday", lastday);

Works with different months and years.
let wDate = new Date();
let dDay = wDate.getDay() > 0 ? wDate.getDay() : 7;
let first = wDate.getDate() - dDay + 1;
let firstDayWeek = new Date(wDate.setDate(first));
let lastDayWeek = new Date(wDate.setDate(firstDayWeek.getDate()+6));
console.log(firstDayWeek.toLocaleDateString());
console.log(lastDayWeek.toLocaleDateString());

Nice suggestion but you got a small problem in lastday.
You should change it to:
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);

The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.
let startOfWeek = moment().startOf("isoWeek").toDate();
let endOfWeek = moment().endOf("isoWeek").toDate();

We have added jquery code that shows the current week of days from monday to sunday.
var d = new Date();
var week = [];
var _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (let i = 1; i <= 7; i++) {
let first = d.getDate() - d.getDay() + i;
let dt = new Date(d.setDate(first));
var _day = _days[dt.getDay()];
var _month = _months[dt.getMonth()];
var _date = dt.getDate();
if(_date < 10 ){
_date = '0' +_date;
}
var _year = dt.getFullYear();
var fulldate = _day+' '+_month+' '+_date+' '+_year+' ';
week.push(fulldate);
}
console.log(week);

An old question with lots of answers, so another one won't be an issue. Some general functions to get the start and end of all sorts of time units.
For startOf and endOf week, the start day of the week defaults to Sunday (0) but any day can be passed (Monday - 1, Tuesday - 2, etc.). Only uses Gregorian calendar though.
The functions don't mutate the source date, so to see if a date is in the same week as some other date (week starting on Monday):
if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
// d is in same week as d1
}
or in the current week starting on Sunday:
if (d >= startOf('week') && d <= endOf('week')) {
// d is in the current week
}
// Returns a new Date object set to start of given unit
// For start of week, accepts any day as start
function startOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(d);
e.setHours(23,59,59,999);
// Define methods
let start = {
second: d => d.setMilliseconds(0),
minute: d => d.setSeconds(0,0),
hour : d => d.setMinutes(0,0,0),
day : d => d.setHours(0,0,0,0),
week : d => {
start.day(d);
d.setDate(d.getDate() - d.getDay() + weekStartDay);
if (d > e) d.setDate(d.getDate() - 7);
},
month : d => {
start.day(d);
d.setDate(1);
},
year : d => {
start.day(d);
d.setMonth(0, 1);
},
decade: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 10);
},
century: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 100);
},
millenium: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 1000);
}
}
start[unit](d);
return d;
}
// Returns a new Date object set to end of given unit
// For end of week, accepts any day as start day
// Requires startOf
function endOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(date);
e.setHours(23,59,59,999);
// Define methods
let end = {
second: d => d.setMilliseconds(999),
minute: d => d.setSeconds(59,999),
hour : d => d.setMinutes(59,59,999),
day : d => d.setHours(23,59,59,999),
week : w => {
w = startOf('week', w, weekStartDay);
w.setDate(w.getDate() + 6);
end.day(w);
d = w;
},
month : d => {
d.setMonth(d.getMonth() + 1, 0);
end.day(d);
},
year : d => {
d.setMonth(11, 31);
end.day(d);
},
decade: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 10 + 9);
},
century: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 100 + 99);
},
millenium: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 1000 + 999);
}
}
end[unit](d);
return d;
}
// Examples
let d = new Date();
['second','minute','hour','day','week','month','year',
'decade','century','millenium'].forEach(unit => {
console.log(('Start of ' + unit).padEnd(18) + ': ' +
startOf(unit, d).toString());
console.log(('End of ' + unit).padEnd(18) + ': ' +
endOf(unit, d).toString());
});

var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)
I'm using the following code in but because of .toUTCString() i'm receiving the following error as show in image.
if i remove .toUTCString(). output which i receive is not as expected

Small change to #SHIVA's answer which is a changed #Chris Lang answer.
For monday first usage with fix when today is sunday.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return new Date(this.setDate(this.getDate() - (this.getDay() == 0 ? 7 : this.getDay()) + 7));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());

You can try the below one too
let weekBgnDt = new Date();
let weekEndDt = new Date();
let wBeginDateLng, wEndDateLng, diffDays,dateCols=[];
if (weekBgnDt.getDay() > 0) {
diffDays = 0 - weekBgnDt.getDay();
weekBgnDt.setDate(weekBgnDt.getDate() + diffDays)
}
weekEndDt = weekEndDt.setDate(weekBgnDt.getDate() + 6)
wBeginDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(weekBgnDt);
wEndDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', month:
'2-digit' }).format(weekEndDt);
wBeginDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekBgnDt);
wEndDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekEndDt);
console.log(wBeginDate, "-", wBeginDateLng)
console.log(wEndDate, "-", wEndDateLng)
for(let i=weekBgnDt;i<=weekEndDt;){
dateCols.push(new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(i));
i=weekBgnDt.setDate(weekBgnDt.getDate()+1)
}
console.log({wBeginDate,wBeginDateLng,wEndDate,wEndDateLng,dateCols})
The result will be printed as
{ wBeginDate: "16/05/2021", wBeginDateLng: "16 May 2021", wEndDate: "22/05/2021", wEndDateLng: "22 May 2021", dateCols: Array ["16/05/2021", "17/05/2021", "18/05/2021", "19/05/2021", "20/05/2021", "21/05/2021", "22/05/2021"] }

The right way to get the first and last date of the current week with appropriate month & year is as below
const curr = new Date();
const first = curr.getDate() - curr.getDay() + 1; // Start from Monday
const firstDate = new Date(curr.setDate(first));
const lastDate = new Date(curr.setDate(firstDate.getDate() + 6));
console.log(firstDate.toLocaleDateString(), lastDate.toLocaleDateString());

You can use this function, it works with first and last day of the week in different months or years
const getFirstAndLastDayOfTheWeek = () => {
// The starting time is the same current
let a = new Date();
let b = new Date();
const weekDay = a.getDay();
if (weekDay === 0) {
a.setDate(a.getDate() - 6);
} else if (weekDay === 1) {
b.setDate(b.getDate() + 7 - b.getDay());
} else if (weekDay >= 1) {
a.setDate(a.getDate() - a.getDay() + 1);
b.setDate(b.getDate() + 7 - b.getDay());
}
return { firstWeekDate: a, lastWeekDate: b };
}
console.log(getFirstAndLastDayOfTheWeek());

Related

Google Sheets getDay() Shows an Incorrect Value

Date() shows the correct date while getDay() shows an incorrect value.
function Test()
{
const date = new Date();
const dateToday = Utilities.formatDate(new Date(), "GMT+8", "MM/dd/YYYY");
const dateYesterday = Utilities.formatDate(new Date(new Date().setDate(date.getDate() - 1)), "GMT+8", "MM/dd/YYYY");
var day = date.getDay();
var a = SpreadsheetApp.getActiveSheet().getRange(3, 2);
switch (day)
{
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
}
a.setValue("Today is " + day + " " + dateToday + ". Yesterday was " + dateYesterday);
}
When this code was executed in Google Sheet, it will output below:
Today is Tuesday 04/21/2022. Yesterday was 04/20/2022
The dates are correct while the day shows Tuesday which is incorrect. It's Thursday right now.
As another approach, in your situation, how about the following modification?
Modified script:
function sample() {
const date = new Date();
const dateToday = Utilities.formatDate(new Date(), "GMT+8", "MM/dd/YYYY");
const dateYesterday = Utilities.formatDate(new Date(new Date().setDate(date.getDate() - 1)), "GMT+8", "MM/dd/YYYY");
const day = Utilities.formatDate(new Date(), "GMT+8", "EEEE"); // Added
const a = SpreadsheetApp.getActiveSheet().getRange(3, 2);
a.setValue("Today is " + day + " " + dateToday + ". Yesterday was " + dateYesterday);
}
In this modification, the day name is retrieved using Utilities.formatDate like Utilities.formatDate(new Date(), "GMT+8", "EEEE").
Reference:
formatDate(date, timeZone, format)
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
Sunday is 0, Monday is 1, etc.
docs
And example with a less length implementation:
const getDayofWeek = x => x === 0 ? 'Sunday' : x === 1 ? 'Monday' : x === 2 ? 'Tuesday' : x === 3 ? 'Wednesday' : x === 4 ? 'Thursday' : x === 5 ? 'Friday' : x === 6 ? 'Saturday' : "Invalid Day";
for (i = 0; i < 8; i++) {
console.log(getDayofWeek(i))
}
Try
function test() {
const dayOfTheWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
const date = new Date();
console.log(dayOfTheWeek[date.getDay()])
}
const dayOfTheWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
const date = new Date();
console.log(dayOfTheWeek[date.getDay()])
The most important thing is to check your timezone in your script editor : go to your script editor, ckick on the gear on the left hand side, check the third box, go back to script editor and review in appsscript.json, hange timezone according to your locale
Try it this way:
function Test() {
const dt = new Date();
const dateToday = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy");
const dateYesterday = Utilities.formatDate(new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() - 1), Session.getScriptTimeZone(), "MM/dd/yyyy");
var d = dt.getDay();
var a = SpreadsheetApp.getActiveSheet().getRange(3, 2);
var day;
switch (d) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
Logger.log("Today is " + day + " " + dateToday + ". Yesterday was " + dateYesterday)
a.setValue("Today is " + day + " " + dateToday + ". Yesterday was " + dateYesterday);
}

Join Date and time for events from sheet to calendar [duplicate]

This question already has an answer here:
Google Apps Script: Concatenating date and time
(1 answer)
Closed 10 months ago.
With this code I can send the events directly to google calendar from google sheets. The start date and end date are on two different columns (col D and col F), the problem is that I need also the time that are on others two columns (col E and col G).
How could I join startDate with date+time and endDate with date+time?
function sendToCalendar() {
var spreadsheet = SpreadsheetApp.getActive().getSheetByName('XCALENDAR')
var calendarID = spreadsheet.getRange("O1").getValue();
var eventCal = CalendarApp.getCalendarById(calendarID);
var signups = spreadsheet.getRange("A5:P5").getValues();
for (x=0; x<signups.length;x++)
{
var shift = signups[x];
var startTime = shift[3];
var endTime = shift[5];
var nameevent= shift[1];
var desc= shift[13];
var color = shift[15];
var event = eventCal.createEvent(nameevent, startTime, endTime,{description:desc});
if(color){
event.setColor(CalendarApp.EventColor[color]);
}
}
}
To concatenate date (d) and time (t), you can do it this way
new Date(d.getFullYear(), d.getMonth(), d.getDate(), t.getHours(), t.getMinutes(), t.getSeconds())
try with
function createEvent() {
// A = title, B = description, C = location, D = begin .. E = at, F = end ... G = at
const myCalend = CalendarApp.getCalendarById("xxxxxxxxxxxx#gmail.com");
const sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
const [headers, ...data] = sh.getRange('A1:H' + sh.getLastRow()).getValues()
const colID = 8; // H
data.forEach((r, index) => {
if (r[colID - 1] == '') {
let [title, desc, loc] = [r[0], r[1], r[2]]
let [bd, bh, ed, eh] = [r[3], r[4], r[5], r[6]]
let id = (myCalend.createEvent(
title,
new Date(bd.getFullYear(), bd.getMonth(), bd.getDate(), bh.getHours(), bh.getMinutes(), bh.getSeconds()),
new Date(ed.getFullYear(), ed.getMonth(), ed.getDate(), eh.getHours(), eh.getMinutes(), eh.getSeconds()),
{
description: desc,
location: loc
}).getId())
sh.getRange(index + 2, colID).setValue(id)
}
})
}
edit
according to your spreadsheet, and assuming that dates are as dd/MM/yyyy, you can use (the eventID will be stored in column M=13 and prevent duplicating event)
function sendToCal() {
var spreadsheet = SpreadsheetApp.getActive().getSheetByName('Foglio1')
let eventCal = CalendarApp.getCalendarById("xxxxxxxxx#gmail.com");
var signups = spreadsheet.getRange("A2:M" + spreadsheet.getLastRow()).getDisplayValues();
var col = 13; // M
for (x = 0; x < signups.length; x++) {
var shift = signups[x];
if (shift[(col - 1)] == '') {
let [d, e, f, g] = [shift[3].split("/"), shift[4].split(":"), shift[5].split("/"), shift[6].split(":")]
let [nameevent, desc, color] = [shift[1], shift[11], shift[12]]
var startTime = new Date(parseInt(d[2]), parseInt(d[1])-1, parseInt(d[0]), parseInt(e[0]), parseInt(e[1]), 0)
var endTime = new Date(parseInt(f[2]), parseInt(f[1])-1, parseInt(f[0]), parseInt(g[0]), parseInt(g[1]), 0)
var event = eventCal.createEvent(nameevent, startTime, endTime, { description: desc });
spreadsheet.getRange(+x + 2, col).setValue(event.getId())
if (color) {
event.setColor(CalendarApp.EventColor[color]);
}
}
}
}
Current Date and Time
function currentdatetime() {
const second = 1000;
const minute = 60 * second;
const hour = minute * 60;
const day = hour * 24;
const dt = new Date();
const dtv = dt.valueOf();
const td = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate())
const dv = td.valueOf();
const d = dtv - dv;
let hours = Math.floor(d % day / hour);
let minutes = Math.floor(d % day % hour / minute);
let seconds = Math.floor(d % day % hour % minute / second);
Logger.log(`Date: ${td.getMonth() + 1}/${td.getDate()}/${td.getFullYear()} - Time:${hours}:${minutes}:${seconds}`)
}
Execution log
9:05:08 AM Notice Execution started
9:05:09 AM Info Date: 5/4/2022 - Time:9:5:9
9:05:09 AM Notice Execution completed
A simpler way
function currentdatetime() {
const dt = new Date();
Logger.log(`Date: ${dt.getMonth() + 1}/${dt.getDate()}/${dt.getFullYear()} - Time:${dt.getHours()}:${dt.getMinutes()}:${dt.getSeconds()}`)
}
Execution log
9:11:19 AM Notice Execution started
9:11:20 AM Info Date: 5/4/2022 - Time:9:11:20
9:11:20 AM Notice Execution completed
Super simple way
function currentdatetime() {
Logger.log(Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"MM/dd/yyyy - HH:mm:ss"))
}
Execution log
9:16:22 AM Notice Execution started
9:16:23 AM Info 05/04/2022 - 09:16:23
9:16:23 AM Notice Execution completed
Joining date and time
function currentdatetime(M=5,d=4,y=2022,H=9,m=28,s=0) {
const dt = new Date(y,M-1,d,H,m,s);
Logger.log(Utilities.formatDate(dt,Session.getScriptTimeZone(),"MM/dd/yyyy HH:mm:ss"));
return dt;
}
Execution log
9:29:38 AM Notice Execution started
9:29:39 AM Info 05/04/2022 09:28:00
9:29:39 AM Notice Execution completed

How to check if date in a cell + 5 = today? (Google Apps Script + Google Sheets)

I'm trying to get a date from a cell, add 5 days to it, and check if that date is today. Here's what I've tried:
function test() {
sheet = SpreadsheetApp.getActive();
var today = new Date(new Date().setHours(0,0,0,0));
var weekStartDate = sheet.getRange('B5').getValue().getTime();
var newDate1 = new Date(new Date().setHours(0,0,0,0));
var newDate5 = new Date(new Date().setHours(0,0,0,0));
newDate1.setTime(weekStartDate + (1*24*60*60*1000));
newDate5.setTime(weekStartDate + (5*24*60*60*1000));
if(newDate5==today){
var answer = 'Yes';
} else{
var answer = 'No';
}
Logger.log(today);
Logger.log(newDate1);
Logger.log(newDate5);
Logger.log(answer);
}
The log shows:
11:29:59 AM Info Wed Jul 21 00:00:00 GMT-04:00 2021
11:29:59 AM Info Sat Jul 17 00:00:00 GMT-04:00 2021
11:29:59 AM Info Wed Jul 21 00:00:00 GMT-04:00 2021
11:29:59 AM Info No
How do I get "answer" to return "Yes"?
Screenshot
To compare two dates, we use values of these dates. This means if you changed newDate5 == today with newDate5.valueOf() == today.valueOf() it will return Yes.
Here is a simplified version of your code:
function test() {
var sheet = SpreadsheetApp.getActive();
var today = new Date().setHours(0,0,0,0).valueOf();
var dateToCompare= new Date(sheet.getRange('B5').getValue()).valueOf();
var dayInMs = 24*60*60*1000
Logger.log(today);
Logger.log(dateToCompare);
Logger.log(today == dateToCompare + 5*dayInMs);
}
Just in case
function myFunction() {
// date from cell 'A1'
var date = SpreadsheetApp.getActiveSheet().getRange('A1').getValue();
// today
var today = new Date();
// function to add 5 days to a date
const five_days_later = (d) => new Date(d.setDate(d.getDate() + 5));
// function to compare two dates
const if_same_date = (d1, d2) => d1.getDate() == d2.getDate() &&
d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear();
// test
Logger.log(if_same_date(five_days_later(date), today));
}
var now = new Date();
var then = new Date("2021-07-16");
const to_str = x => '' + x.getYear() + x.getMonth() + x.getDate();
const if_same_date = (d1, d2) => to_str(d1) == to_str(d2);
const plus_days = (date, gap) => new Date(date.valueOf() + gap*24*60*60*1000);
console.log(if_same_date(now, plus_days(then, 5)));

Calculate time based on business working hours

Add numbers of hours to a timestamp and make sure that the output is within working hours.
For example:
Open Time -> 9:00 AM
Close Time -> 6:00 PM
First Date -> 12/1/2020 12:00 PM
Add Time -> 7 hours
Result -> 13/1/2020 10:00 AM
I am trying to achieve this using GAS ES5/ES6
Already tried a formula which is very close to this logic:
Cell A7 = First Date
Cell G5 = Add Time
Cell B1 = 9/24-18/24
Sheet2!A:A = List of Holidays to Skip
0000011 = Skips Saturday and Sunday
=if(A7,if(and(hour(A7+G$5)>9,(hour(A7+G$5)<18)),A7+G$5,workday.intl(int(A7+G$5+$B$1),1,"0000011",Sheet2!A:A)+hour(A7+G$5+$B$1)/24),"")
I think you are looking for this:
function myFunction() {
var open_h = 9 // 24h
var close_h = 18 //24h
var add_h = 7 // number of hours
var d = new Date();
d.setDate(d.getDate() + (1 + 7 - d.getDay()) % 7);
next_Monday = d.getDate()
var first_date = new Date() ;
var end_date = new Date();
end_date.setTime(end_date.getTime() + (add_h*60*60*1000))
if (end_date.getDate()>first_date.getDate()){
end_date.setDate((new Date()).getDate());
end_date.setHours(23, 0 , 0);
}
if (end_date.getHours()>=close_h){
if (end_date.getDay() == 5 || end_date.getDay() == 6 || end_date.getDay() == 0 ) {end_date.setDate(next_Monday) }
else {end_date.setDate(end_date.getDate() + 1)} // tomorrow
var end_time = end_date.getHours()-close_h + open_h
end_date.setHours(end_time, 0, 0);
}
Logger.log(end_date)
} // end function
end_date will give you the desired result.
Edit: it also takes weekends into consideration.

Number of working days between two dates in Google Apps Script

Could anyone please help with generating number of working days between two dates in Google Apps Script.
Thank you.
Based on the answer given here: How do I calculate number of given weekday between range using Moment JS?
It works similar in AppsScript
function workdays_between(start_date_string, end_date_string) {
var startDate = new Date(start_date_string)
var endDate = new Date(end_date_string)
// Validate input
if (endDate <= startDate) { return 0; }
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) { days -= 2; }
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) { days--; }
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) { days--; }
return days
}
function test_it() {
let start_date_string = "March 12, 2021"
let end_date_string = "October 15, 2021"
console.log(workdays_between(start_date_string, end_date_string) + " workdays between " + start_date_string + " and " + end_date_string)
}
From user KBA (https://stackoverflow.com/users/453331/kba) from response How do I calculate number of given weekday between range using Moment JS?:
var firstDate = new Date("March 1, 2015");
var secondDate = new Date("March 25, 2015");
function getWeekdaysBetweenDates(firstDate, secondDate, dayOfWeek) {
var MILISECONDS_IN_DAY = 86400000;
function getNextDayOfWeek(date, dayOfWeek) {
date.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);
return date;
}
firstDate = getNextDayOfWeek(firstDate, dayOfWeek);
if (firstDate > secondDate) {
return 0;
}
return 1 + Math.floor(((secondDate - firstDate) / MILISECONDS_IN_DAY) / 7);
}