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..
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.
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
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
Related
var date = Utilities.formatDate(new Date(), "GMT-8", "m/dd/yyyy")
if (formS.getRange("B7").getValue() != " " && formS.getRange("B7").getValue() != date)
{
SpreadsheetApp.getUi().alert("Please Enter A Valid Date");
return
}
Trying to make the condition above check if the cell is not empty and that it does not contain a date prior to Today's Date
function myfunk() {
const ss = SpreadsheetApp.getActive();
const formS = ss.getSheetByName('formS');
const dtv = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).valueOf();
if (!formS.getRange("B7").isBlank() && new Date(formS.getRange("B7").getValue()).valueOf() < dtv) {
SpreadsheetApp.getUi().alert("Please Enter A Valid Date");
return;
}
}
Checking Dates in Apps Script
In general you can use the Date object as you would in normal JavaScript code. There are just one main thing to bear in mind if your script needs to be sensitive to timezones.
The timezone is defined in the manifest:
This cannot be changed dynamically. So if you need to be sensitive to them, then you will need to manage the offsets in your code.
Your script
This line:
var date = Utilities.formatDate(new Date(), "GMT-8", "m/dd/yyyy")
Returns a string. Not a date object, so you can't compare it to another date object, such as what is returned from a sheet value if it is formatted as a date.
You could use Regex or split to get the year and month and compare it that way, but then you may run into issue when you use the script on the 1st of January. This is because by simply comparing the year, month and date of 31/12/2021 with 01/01/2022, then your conditional statements would be a bit tricky. Possible, but maybe a bit hard to read.
Initializing to midnight
What follows is one approach to take to carry out this comparison in a relatively simple way.
It seems convenient to get a date object initialized to 00:00:00 of today. Then you can quickly compare the date using Unix time.
var now = new Date()
now.setHours(0)
now.setMinutes(0)
now.setSeconds(0)
now.setMilliseconds(0)
You can also do this in a more concise way like this:
var now = new Date()
now.setHours(0,0,0,0);
Then you can use the getTime() method on the date objects to get Unic time in milliseconds and compare them.
var dateToCheck = formS.getRange("B7").getValue()
if (
!(dateToCheck instanceof Date) || // If value is not instance of a Date object
dateToCheck.getTime() <= now.getTime() // If date is before 00:00:00 today.
) {
SpreadsheetApp.getUi().alert("Please Enter A Valid Date");
return
}
}
Which seems like a concise way to do the comparison you are looking for.
References
Apps Script Dates
JS Date object
I have a template sheet inside a workbook that I want to copy to a new workbook that is not yet created. I want this to run on the 29th of each month and do the following:
Take a Spreadsheet names "Template" and the sheet named “Template..2020.”
Create a new Spreadsheet called "December 2020" for example, and rename the first tab to 12.01.20, which I can then copy and rename for every day of the month.
I have tried a few copy functions with time triggers but they have required a blank workbook to be open already.
Example Script
This script
Function createSheetFromTemplate
Uses the date object to get information about today's date and extracts the year, month, day etc.
Gets the template from another sheet using SpreadsheetApp.openById
Creates a new Sheet based on information from today's date.
Copies the template sheet and renames it based on the date.
Function createTrigger
Using ClockTriggerBuilder, creates a trigger to run on the 29th of each month.
Disclaimer: At the moment this script just creates a new Spreadsheet with today's month and a new sheet named with today's date. I understand you may be looking to create a sheet for next month. This problem is probably best served by another question - perhaps look here.
function createSheetFromTemplate() {
// Getting details of today's date
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth() + 1
let monthName = date.toLocaleString('default', { month: 'long' });
let day = date.getDate()
console.log(year, monthName, day)
// Get template based on year
let templateSpread = SpreadsheetApp.openById("1H7GBVxK4f0nmYR5xfZawy6nreDTCZaj76-dKE9eOtUE")
let templateSheet = templateSpread.getSheetByName("Template_" + year)
// Create new Spreadsheet with renamed template
let newSpread = SpreadsheetApp.create(monthName + " " + year)
let newSheet = templateSheet.copyTo(newSpread).setName(year.toString().substring(2,4) + "." + month + "." + day)
let sheetToDelete = newSpread.getSheetByName("Sheet1")
newSpread.deleteSheet(sheetToDelete)
}
// Create trigger to run on 29th of each month.
function createTrigger() {
ScriptApp.newTrigger('createSheetFromTemplate')
.timeBased()
.onMonthDay(29)
.create();
}
References
date object
SpreadsheetApp.openById
ClockTriggerBuilder
I would like programably enter the date into a cell and format it to include the Day of the week (Mon, Tue, Wed,...). If I use the .setNumberFormat method (which I would prefer to do because it keeps the info as a date), the simpleDateFormat for Day of the week does not work. If I use Utilities.formatDate I can use 'EEE, MM/dd' and it will show up correctly, but I lose the date format.
function setformat(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lab = ss.getSheetByName("test2");
// This is what I want to use but the day of the week 'EEE' doesn't work
var todaySNF = new Date();
lab.getRange("a1").setValue(todaySNF);
lab.getRange("a1").setNumberFormat('EEE, MM/dd'); // Should read Wed, 09/23 but reads EEE, 09/23 instead.
var cellA1asDate = new Date(lab.getRange("a1").getValue());
Logger.log(cellA1asDate);}
use this instead :
lab.getRange("a1").setNumberFormat('DDD, MM/dd');
I have some dates in a Google Spreadsheet that I'm bringing in to a script like this:
var JCstartDateFix = Math.floor(Date.parse(JCstartDate) / 86400000) + 25570;
var todaysDateFix = Math.floor(Date.parse(todaysDate) / 86400000) + 25570;
How do I do the opposite of this at the end of the script to change it back into a mm/dd/yyyy formatted date?
Thanks in advance for any help on this.
Here's the whole script:
function projectedDate(JCstartDate, overallPercent, pace, todaysDate, HSstartDate, DaysInHS) {
//converts dates to a number of days
var JCstartDateFix = Math.floor(Date.parse(JCstartDate) / 86400000) + 25570;
var todaysDateFix = Math.floor(Date.parse(todaysDate) / 86400000) + 25570;
//This says that there's no projected date since the student hasn't started high school yet
if(HSstartDate == ""){
return "HS not started";
}
//This calculates grad date if the student's been here more than 8 months or if their percent is over 80.
else if(DaysInHS >= 200 || overallPercent >=80){
var percentPerDay = overallPercent/(DaysInHS);
var daysLeft = (100 - overallPercent) / percentPerDay;
if((todaysDateFix + daysLeft) > (JCstartDateFix +730)){
return "You are not on track to complete.";
}
else{
return (todaysDateFix + daysLeft);
}
}
//This calculates grad date if the student's been at JC less than 8 months
else{
if(JCstartDateFix + 600 - pace > JCstartDateFix + 730){
return "You are not on track to complete.";
}
else{
return (JCstartDateFix+600-pace);
}
}
}
I work in a school where students start at different times and work at their own pace. They have a 2 year limit to finish. So this script estimates their graduation date based on when they started and how fast they're going. It uses different formulas depending on how long they've been here. I'm happy with the dates I get on my spreadsheet, but if I format them from the spreadsheet, another script doesn't correctly pick up the text strings and gives a date in 1969 instead.
I think what I need to do is change the lines that return numbers so that those numbers are formatted as dates. I just don't know how. Thanks again!
The value you get with Date.parse() is in milliseconds, you divide it by the number of milliseconds in a day so I guess you obtain the number of days since the JS reference date, rounded to the lowest integer and then add a constant value of 25570.
What is the result supposed to be ?
It seems that it should be a number of day from the ref date but that's quite far in the future !! (about 70 years) Is this right ? could you clarify ?
Anyway, what you should do is to get a value in milliseconds again and use new Date(value in mSec) to get a date object. From there Utilities.formatDate will allow you to get any display format you want.
ref : http://www.w3schools.com/jsref/jsref_obj_date.asp
https://developers.google.com/apps-script/class_utilities#formatDate
As long as the value that you're setting in the spreadsheet is a Date object in apps script, it will appear as a date. The format will be under the control of the spreadsheet, of course, but it defaults to mm/dd/yyyy.
For example, you could just change your existing code to render Date objects. Then, when you call setValue() you will write a date out to the spreadsheet.
var JCstartDateFix = new Date(Math.floor((Date.parse(JCstartDate) / 86400000) + 25570)*86400000);
var todaysDateFix = new Date(Math.floor((Date.parse(todaysDate) / 86400000) + 25570)*86400000);
There is an option to write a script and bind it to a trigger. The question is, how to get the current time in the script body?
function myFunction() {
var currentTime = // <<???
}
use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)
function myFunction() {
var d = new Date();
var timeStamp = d.getTime(); // Number of ms since Jan 1, 1970
// OR:
var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}
I considered with timezone in my Google Docs like this:
timezone = "GMT+" + new Date().getTimezoneOffset()/60
var date = Utilities.formatDate(new Date(), timezone, "yyyy-MM-dd HH:mm"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
my script for Google docs
Use the Date object provided by javascript. It's not unique or special to Google's scripting environment.
Anyone who says that getting the current time in Google Sheets is not unique to Google's scripting environment obviously has never used Google Apps Script.
That being said, do you want to return current time as to what? The script user's timezone? The script owner's timezone?
The script timezone is set in the Script Editor, by the script owner. But different authorized users of the script can set timezone for the spreadsheet they are using from File/Spreadsheet settings menu of Google Sheets.
I guess you want the first option. You can use the built in function to get the spreadsheet timezone, and then use the Utilities class to format date.
var timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
var date = Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "EEE, d MMM yyyy HH:mm")
Alternatively, get the timezone offset from UTC time using Javascript's date method, format the timezone, and pass it into Utilities.formatDate().
This requires one minor adjustment though. The offset returned by getTimezoneOffset() runs contradictory to how we often think of timezone. If the offset is positive, the local timezone is behind UTC, like US timezones. If the offset is negative, the local timezone is ahead UTC, like Asia/Bangkok, Australian Eastern Standard Time etc.
const now = new Date();
// getTimezoneOffset returns the offset in minutes, so we have to divide it by 60 to get the hour offset.
const offset = now.getTimezoneOffset() / 60
// Change the sign of the offset and format it
const timeZone = "GMT+" + offset * (-1)
Logger.log(Utilities.formatDate(now, timeZone, 'EEE, d MMM yyyy HH:mm');
The Date object is used to work with dates and times.
Date objects are created with new Date().
var date= new Date();
function myFunction() {
var currentTime = new Date();
Logger.log(currentTime);
}