Reputation: 159
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..
Upvotes: 10
Views: 23936
Reputation: 101
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
Upvotes: 1
Reputation: 2532
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.
Upvotes: 16
Reputation: 1305
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
Upvotes: 6