Reputation: 17
So when I run the code I want it to make a new sheet with the date 3 days later than today. Ex.: today is 2206 and 3 days later is 2506. So it has to be like DDMM.
And if it is like June 30th it needs to become July 3rd and not June 33th (It doesn't exist).
Here's it for today...I tried some for +3 days but it didn't work...:
function addSheet(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var dateM = Utilities.formatDate(new Date(), "GMT+1", "MM");
var dateD = Utilities.formatDate(new Date(), "GMT+1", "dd");
if(Number(dateD)<10){
dateD = String("0" + dateD);
};
sheet.insertSheet(dateD+dateM);
var time = dateD.getDate();
sheet.insertSheet(time);
};
Upvotes: 0
Views: 74
Reputation: 14537
Short variant. Just in case:
function addSheet() {
const three_days_later = (d) => new Date(d.setDate(d.getDate() + 3));
const name = Utilities.formatDate(three_days_later(new Date()), 'Etc/GMT', 'ddMM');
SpreadsheetApp.getActiveSpreadsheet().insertSheet(name);
}
With a local time zone (credits to k.b). Not so short, though:
function addSheet() {
const three_days_later = (d) => new Date(d.setDate(d.getDate() + 3));
const ss = SpreadsheetApp.getActiveSpreadsheet();
const name = Utilities.formatDate(
three_days_later(new Date()),
ss.getSpreadsheetTimeZone(), 'ddMM'
);
ss.insertSheet(name);
}
Upvotes: 2
Reputation: 22032
Here is one approach for building the sheet name you need:
let sheetDate = new Date();
sheetDate.setDate(sheetDate.getDate() + 3);
let mo = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(sheetDate);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(sheetDate);
let sheetName = `${da}${mo}`;
console.log(sheetName);
You can use this in a function as follows:
function addSheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
let sheetDate = new Date();
sheetDate.setDate(sheetDate.getDate() + 3);
let mo = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(sheetDate);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(sheetDate);
let sheetName = `${da}${mo}`;
sheet.insertSheet(sheetName);
}
See here for more information about the datetime formatter used in the above example.
There are probably more concise approaches, but this shows an approach which can be customized in a wide variety of different ways.
Upvotes: 3