Hello I am trying to set a date into Google Doc's document header. Now, here is the code I got so far but it won't change the current date inside my document's header as I close the document and re-open it any ideas what might be wrong with this code? on the document this is how I have my date: "Daily Report of: 10-19-20"
function onOpen() {
var date = Utilities.formatDate(new Date(), "GMT", "MM-dd-yyyy");
var pattern = "\\d{2}-\\d{2}-\\d{4}";
var header = DocumentApp.getActiveDocument().getHeader();
header.editAsText().replaceText(pattern, date);
}
Also please note that I do have a date in this format inside my header: 15-10-2020. But this should update to give me today's date. However, that's not happening.
Thanks
It is not happening because on your pattern you are looking for a date like 18.10.2020
Instead of using your pattern with . change it to be with -:
var pattern = "\\b\\d{2}\\-\\d{2}\\-\\d{4}\\b";
Also, I would recommend running the script from the Script editor the first time and checking if it works, then doing it by closing and re-opening the document.
I believe your goal as follows.
You want to update the text of 15-10-2020 at the header using var date = Utilities.formatDate(new Date(), "GMT-6", "dd-MM-yyyy") in Google Document using Google Apps Script.
In this case, I would like to propose to modify the value of pattern as follows.
Modified script:
Please modify as follows and test it again.
From:
var pattern = "\\b\\d{2}\\.\\d{2}\\.\\d{4}\\b";
To:
var pattern = "\\d{2}-\\d{2}-\\d{4}";
Added:
From your updated question, it was found that your value on Google Document was Daily Report of: 10-19-20. In this case, how about the following modification?
From:
var pattern = "\\b\\d{2}\\.\\d{2}\\.\\d{4}\\b";
To:
var pattern = "\\d{1,2}-\\d{1,2}-\\d{2,4}";
By this modification, the values of 10-19-20 and 10-19-2020 can be updated.
Related
I have searched the site for similar questions but I did not find an answer specific to my situation. I am trying to display the current date in this formate: dd-MMM-yy, without the UTC time at the end. In the past in other functions I was able to have success using this: .setNumberFormat but in the function I am working on now, it won't work and it displays the full date.
This is my code I am using it in:
function updateLTD(e) {
// Code designed to insert current date to the "LTD" sheet.
var date = new Date();
if (e.range.columnStart != 1 || !e.value) return;
e.range.offset(0,3).setValue(date).setNumberFormat("dd-MMM-yy");
}
How to make this work in my current code? I appreciate any suggestions.
I'm reading an entire Gmail emails (inbox/sent/trash...), and try to create folders in google drive according to dates.
So folders should be categorized like (...,2019,2020, 2021). Each folder contains all emails in this year in my Gmail.
I managed to create the folders, getting messages through using Threads, all these things works fine, but I couldn't extract the year of the message only.
As when I use Threads[0].getMessages()[0].getDate() what is returned is date and time of this message. which I can't extract the year only from it.
I tried to split the date, but this is not string.
I tried to make smth like Threads[0].getMessages()[0].getDate().getYear() it returned 120!!!
I tried to see if I can access it as an array, [index], it returned null
I tried to parse it to Date(), but I couldn't get use of it too.
Is there is anyway that allows me to extract only the year from this format.
This is part of the script where i'm trying to fetch the date I'm using.
function GetAttachmentsWithTime() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
sheet.setActiveSheet(sheet.getSheetByName('Sheet1'));
var start = 0;
var end = 10;
var filter = "has:attachment";
var threads = GmailApp.search(filter,start,end);
Logger.log(threads[0].getMessages()[0].getDate())
}
Are you using the V8 runtime?
If so, see this migration guide. It says:
In the V8 runtime, Date.prototype.getYear() returns the year minus
1900 instead as required by ECMAScript standards.
So emails from the year 2020 would return 120 (i.e. 2020 - 1900 = 120).
To fix this, use .getFullYear():
When migrating your script to V8, always use
Date.prototype.getFullYear(), which returns a four-digit year
regardless of the date.
I'm creating a script in Apps Script that will count a habit streak. It will use today's date to find the correct column on the Sheet and count backwards from there until it hits a missed day. To get today's date, I'm trying to use:
Utilities.formatDate(new Date(), "EST", "yyyy.MM.dd");,
which keeps giving me the error:
"Cannot find method formatDate(object,string,string)"
My code uses exactly the same syntax as they show on the references page other than my changing the time zone from "GMT" to "EST", but changing it back to "GMT" or to "GMT-5" didn't fix it, so I'm kind of at a loss.
I think it's an issue creating the date object from "new Date()", as I've tried to use other date methods like Date.now() to which it throws up "TypeError: Cannot find function now in object [object Object]." I figured this may be something to do with my scopes but I checked and it looked like I had all the ones I needed.
I also tried creating the Date object separately and then passing the variable into formatDate but had the same result.
Code I've tried is:
var day = Utilities.formatDate(day, "GMT-5", "yyyy.MM.dd");
------
var day = Utilities.formatDate(new Date(), "EST", "yyyy.MM.dd");
------
var day = new Date();
var day = day.now();
Let me know if you need more to go off of than that. Any help is appreciated, even if it's just using a different method to set a variable equal to today's date, thanks!!!
I got same situation, but i can fix it.
You did Utilities.formatDate(new Date(), "EST", "yyyy.MM.dd");
You may change like the following
var date = new Date;
var today= new Date(date.getFullYear(), date.getMonth(), date.getDate());
today = Utilities.formatDate(today, "EST", "yyyy/MM/dd");
Try running the following test in your script:
function test() {
Logger.log(Utilities.formatDate(new Date(), "EST", "yyyy.MM.dd"));
// output: "2020.02.07"
}
I got the expected output. As #TheMaster points out, you probably have conflicting variable names somewhere.
As soon as I created a new project the utilities starting working properly.
From #TheMaster's comments:
Try isolating the issue> create a new project>add in only one function> one line with utilities. See minimal reproducible example
You probably have conflicting variables somewhere, like variables with the same name. day is a common name... you might've used it in any of the other file scripts attached.
I am using Google Script to export some calendar events to a spreadsheet; the relevant portion of my script is below:
var details=[[mycal,events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), events[i].getStartTime(), myformula_placeholder, ('')]];
var range=sheet.getRange(row,1,1,7);
range.setValues(details);
This code works but the "time" that is put into the spreadsheet is a real number of the form nnnnn.nn. On the spreadsheet itself the date looks great using the integer to the left of the decimal (eg 10/15/2017) but the decimals are part of the value and therefore are part of the spreadsheet value.
My script drops the data into a sheet in my workbook, and another sheet reads the rows of data with the above date types, looking for specific date info from the other sheet using the match function (for today()). That would work fine if I could get rid of the decimals.
How can I use what I have above (if I stray far from what I have found works I will be redoing hours of work) but adding just what is needed to only put into the output spreadsheet the whole number portion so I have a pure date that will be found nicely by my match function using today()?
I have been digging, but errors abound in trying to put it all together. "Parse" looked like a good hope, but it failed as the validation did not like parse used within getStartTime. Maybe I used it in the wrong manner.
Help would be appreciated greatly.
According to the CalendarApp documentation, getStartTime() generates a Date object. You should be able to extract the date and time separately from the date object:
var eventStart = events[i].getStartTime(); // Returns date object
var startDate = eventStart.toDateString(); // Returns date portion as a string
var startTime = eventStart.toTimeString(); // Returns time portion as a string
You could then write one or both of these to your spreadsheet. See the w3schools Javascript Date Reference for more information:
http://www.w3schools.com/jsref/jsref_obj_date.asp
If you If you want to specify the string format, you can try formatDate in the Utilities service:
https://developers.google.com/apps-script/reference/utilities/utilities#formatdatedate-timezone-format
You could just use the Math.floor() function
http://www.w3schools.com/jsref/jsref_floor.asp
which will round the real number to an integer. Your line would then read:
var details=[[mycal,events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), Math.floor(events[i].getStartTime()), myformula_placeholder, ('')]];
I am pretty new to Google Apps Script, so please bear with me.
I am collecting daily interest rates from a bank on Google Sheets, and I am using the following code to append new rows for the rates contained in A5:F5, with column A containing dates.
function recordHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Interest Rates");
var source = sheet.getRange("A5:F5");
var values = source.getValues();
values[0][0] = Utilities.formatDate(new Date(), "GMT+10:00", "yyyy-MM-dd");
sheet.appendRow(values[0]);
};
My issue is this - although I have specified the date format to be "yyyy-MM-dd" the dates in column A in my new rows are created in this format "M/dd/yyyy".
I have tried pre-formatting entire column A with "yyyy-MM-dd" using the drop down Format menu in Google Sheets, but if I run the code above my new row is still in "M/dd/yyyy".
It's as if my code ignores Utilities.formatDate completely. FYI I got the above code from here.
The Utilities.formatDate() utility formats a javascript String. However, when written out to the spreadsheet, the new row of data is interpreted by Google Sheets to determine data types and appropriate formatting, just as if you'd typed it in through the user interface.
Since you've got a recognizable date string, Google Sheets decides it's a Date, stores it as such, and applies the default date format.
You've got two options for making the date in the spreadsheet meet your formatting needs.
Force it to be interpreted as a String, even if it does look like a date.
cell.setValue(Utilities.formatDate(new Date(), "GMT+10:00", "''yyyy-MM-dd"));
// ^^ force string literal
Set the date format for the cell. This will leave the value of the cell as a date, which is useful for calculations.
Date formats follow the SimpleDateFormat specification.
// Cell A1 contains a date
var cell = SpreadsheetApp.getActiveSheet().getRange("A1");
cell.setNumberFormat('yyyy-mm-dd');
Solution :
values[0][0] = Utilities.formatDate(new Date(),
"GMT+10:00", "yyyy-MM-dd").setNumberFormat('yyyy-mm-dd');