Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get week number in google-apps-script

How to get week number in google-apps-script?

For example, this week is Week37, How to get the 37 from google apps script?

Thank you very much..

like image 226
Jiangkun LIU Avatar asked Sep 07 '15 06:09

Jiangkun LIU


People also ask

How do I get week numbers in Google script?

The syntax for the function is WEEKNUM(date), where date is the date you want to find the week number for. An example of how to use WEEKNUM in Google Sheets is shown below. In the example, the week number for January 1, 2019 is 1. The week number for January 2, 2019 is 2.

How do you calculate week number?

The week number is the count of weeks that have passed in the year up to the end of the current week. For example, if it's the second week of the year, the week number is 2. The week where Jan 1 falls counts as the first week for the following year.

How do I extract a week from a date in Google Sheets?

How to get the week number from a date. To get the ISO week number (1-53) from a date in cell A1 , use =ISOWEEKNUM( A1 ) . To get the corresponding year, use =YEAR( A1 -WEEKDAY( A1 , 2)+4) . Read more about =ISOWEEKNUM() and WEEKDAY() in the Google Docs Help Center.

How do I get the date in Google Apps Script?

You can create a date object by passing a formatted date string to the date constructor. For example: const date = new Date('February 17, 2021 13:00:00 -0500');


2 Answers

Maybe there was no such functionality in 2015, but now just you can:

var data = Utilities.formatDate(new Date(), "GMT", "'Week'w"); 
// data = 'Week48' for example

You can use Utilities.formatDate(new Date(), "GMT", "u") which returns the number of the day in a week (1-Monday, 7-Sunday) and update week number depending on its value.

like image 80
Yann Avatar answered Sep 19 '22 00:09

Yann


Add this to the top of your Apps Script:

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
} 

Then you can use the getWeek method, for example to get this week:

var now = new Date();
Logger.log(now.getWeek());

Source: http://javascript.about.com/library/blweekyear.htm

like image 37
Wim den Herder Avatar answered Sep 20 '22 00:09

Wim den Herder