10

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..

Jiangkun LIU
  • 149
  • 2
  • 2
  • 8

3 Answers3

16

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Yann
  • 2,426
  • 1
  • 16
  • 33
6

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

Wim den Herder
  • 1,197
  • 9
  • 13
  • 1
    this will NOT give you an iso week, just a way to approximate it. it also depends if weeks start on Sunday or monday. https://en.m.wikipedia.org/wiki/ISO_week_date – Zig Mandel Sep 07 '15 at 13:15
1

By default, Google Sheets start to count week numbers from Sunday. If u want to start count from Monday you can do something like that:

function getWeek(date) {
  return Number(Utilities.formatDate(new Date(date), "Europe/Kiev", "u")) === 7 ? 
    Number(Utilities.formatDate(new Date(date), "Europe/Kiev", "w")) - 1 : 
    Number(Utilities.formatDate(new Date(date), "Europe/Kiev", "w"));
}

So the code will analyze if the day of the week equal to 7 (Sunday) it will returns (currentWeek - 1), else currentWeek.

And you have to specify timeZone param to your country time zone. This is the second param in Utilities.formatDate, in my case that was "Europe/Kiev", but you can find zone that you need here: https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids

If you need some more information what params you can throw in Utilities.formatDate you can find it here: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

isherwood
  • 58,414
  • 16
  • 114
  • 157
Denis Golubev
  • 96
  • 1
  • 6