I work around this script:
https://developers.google.com/apps-script/articles/helpdesk_tutorial?hl=it
In this code part.
var textApptDate = app.createTextBox();
// Text entered in the text box is passed in to apptDate
textApptDate.setName('apptDate');
var day = new Date();
day.setDate(day.getDate()+1);
textApptDate.setText(Utilities.formatDate(day, "PDT", "MM/dd/yyyy"));
grid.setWidget(0, 0, app.createLabel('Appointment Date:'));
grid.setWidget(0, 1, textApptDate);
I change the code for insert a DatePicker
var day = new Date();
day.setDate(day.getDate()+1);
var textApptDate = app.createDateBox().setName('apptDate').setValue(day);
var handler = app.createServerHandler('change');
handler.addCallbackElement(textApptDate).;
DataPicker work fine but the script don't work fine.
where is the error?
thank you for help me.
raffaele
In the original script the value of the date in the handler function ( var apptDate = e.parameter.apptDate;
) is a string. The manipulations that follow in the code convert that string into a date object.
When you replace the widget by a dateBox the value of var appDate in the handler is not a string anymore, it is already a date object. So the following string manipulations won't work.
You have 2 possibilities :
convert this date object to a string and keep the code as it is (but this is a bit silly in my opinion because it's a kind of 'undo/redo')
Take that difference into account and go directly to the hour setting using the date object as starting value (which will be much more efficient and 'elegant').
Related
I have a simple script that creates and a Gmail Add on. Using Card Service the user can enter values that once submitted send the values to a Google Sheet. Everything works fine accept the date field which returns values such as {msSinceEpoch=1.6145568E12}. Attempts to use Utilities.formatDate fails to rectify this the default value of '1/1/1970' is returned. It is not clear to me why this is the case?
The Card Service includes the following for the date field:
section.addWidget(CardService.newDatePicker().setValueInMsSinceEpoch(Date.now())
.setFieldName('fieldD')
.setTitle(date));
This is followed by a standard action:
var action = CardService.newAction()
.setFunctionName('enterAction');
And a function which inserts the values in the Google Sheet:
function enterAction(e) {
var sheet = SpreadsheetApp.openById("SheetID").getActiveSheet();
....
var inputValues5 = e.formInput['fieldD'];
...
var values = [.....[inputValues5],...];
sheet.getRange(sheet.getLastRow() + 1,1,1,7).setValues([values]);
Any help appreciated.
can you try it like this?
section.addWidget(CardService.newDatePicker().setValueInMsSinceEpoch(new Date())
.setFieldName('fieldD')
.setTitle(date));
or
let newDate = new Date();
section.addWidget(CardService.newDatePicker().setValueInMsSinceEpoch(newDate)
.setFieldName('fieldD')
.setTitle(date));
Also not sure about the .setValueInMsSinceEpoch(), is there another function you can call?
1.6145568E12 is March 1st 2021 in milliseconds since the epoch (this is the expected format). I don't see your code for the formatDate statement, but something like this should work:
var fieldD = e.formInput['fieldD'];
var inputDate = new Date(fieldD.meetingTime.msSinceEpoch);
var inputValues5 = Utilities.formatDate(inputDate,
e.userTimezone.id,
"MM/dd/yyyy HH:mm:ss");
My code creates an event inside Google Calendar, I need to get the value of start time and add 2 hours to get my end time.
Here's an example of the array my function returns:
[[kljlkjl, Manaf, Tue Jun 25 16:00:00 GMT+03:00 2019]]
This is part of the code that I want to fix:
var data = ss.getRange("A"+activeRow+":G"+activeRow).getValues();
if(cellContent === "Manaf") {
Logger.log(data);
Manaf.createEvent(data[0][0],data[0][2],data[0][2],{description: "First call "+ data[0][0]}) ;
Solution
To increment hours by 2, you can utilize getHours() and setHours() methods of the Date built-in object with the instance written into data variable. As you need to increment hours dynamically, you’ll have to pair these methods like this: dateInstance.setHours(dateInstance.getHours()+2).
Sample
So, your script with this modification will look like this (please, note that I also updated your code to work directly with 1-d Array as your range is always one-row):
var data = ss.getRange("A"+activeRow+":G"+activeRow).getValues()[0];
var start = data[2];
var end = new Date(start); //create new Date to persist start;
end.setHours(start.getHours()+2); //add 2 hours;
if(cellContent === "Manaf") {
Manaf.createEvent(data[0],start,end,{description: "First call "+ data[0]});
}
Useful links
Date built-in object reference;
getHours() method deeplink;
setHours() method deeplink;
I have scoured SO and the interwebs and discovered the horror that is date handling in Google Apps Script. I have found conflicting answers about date() and formatDate(), and have yet to find a definitive, working guide that shows the exact steps to take arbitrary text and create a date object
I have a simple ui.Prompt() that asks for a date in human-friendly terms, like "MM-DD-YYYY". I want to do date math on it, so ...
// result from ui.Prompt(), ie "03/01/2019" march 1st
var mytextdate = result.getResponseText();
//I want to do date math, so need a date object ...
var year_num = +mytextdate.substring(6,10);
var month_num = +mytextdate.substring(0,2);
var day_num = +mytextdate.substring(3,5);
var date_mytextdate = new date(year_num, month_num -1, day_num);
The script fails with 'date is undefined' at this point, before I can even do my date math. However I can retrieve the values for year_num, month_num, and day_num without a problem. What else do I need to make `date()' valid?
Make you last line:
var date_mytextdate = Utilities.formatDate(new Date(year_num, month_num -1, day_num),Session.getScriptTimeZone(),"MM-dd-yyyy");
Utilities.formatDate()
I have a question about the date convert:
in sheet, I have a date '05/11/2018', I need to get next date 06/11/2018.
var end=Utilities.formatDate(new Date(coach_date.getTime()+1*3600000*24), 'GMT', 'dd/MM/yyyy');
var start = new Date();
var events = calendar.getEvents(start,end);
it shows the 'end' is string, not object. it has to be getEvents(object,object)
so I used end = new Date(end); it got '11/06/2018', change month from Nov to June.
How could I fix it, then use it on getevents() feature.
Thanks a lot.
Utilities.formatDate() converts the date object into a string. So, use
var end = coach_date.setDate(coach_date.getDate()+1);
In the Google reference documentation I found a short function to convert RFC3339 date string to a valid Date object. The code is very simple and goes like this :
function parseDate(string) {
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
return new Date(parts.join(' '));
}
The problem is that it does not work.(I'm surprised they publish a code that doesn't work... am I missing something ?)
I also had an issue while using JSON to stringify and parse dates because the JSON method returns a UTC value (a Z at the end) and because of that I lose the Time zone information. Google's code does not handle that issue either (even if it worked).
Below is a demo code I used to test it and a solution I wrote to get what I want. Not sure it's very efficient nor well written but at least I get the result I want (I'm executing this code in a script set to GMT+2, Belgium summer time).
I'm open to any suggestion to improve this code.(and that would be the subject of this question)
I added a lot of logs and comments in the code to make it as clear as possible :
function testJSONDate() {
Logger.log('starting value : "2016/3/31 12:00:00"');
var jsDate = JSON.stringify(new Date("2016/3/31 12:00:00"));// time is 12:00 I'm in GMT+2
Logger.log('JSON.stringify value : '+jsDate);
Logger.log('JSON parse jsDate : '+JSON.parse(jsDate)); // time is 10:00, UTC
var jsDateWithoutQuotes = jsDate.replace(/"/,'');
var date = parseDate(jsDateWithoutQuotes);
Logger.log('parsed RFC3339 date using Google\'s code : '+date); // does not return a valid date
var otherFunction = parseDate2(jsDateWithoutQuotes);
Logger.log('parsed RFC3339 date using other code : '+otherFunction); // does return a valid date in my TZ
}
function parseDate(string) {
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
return new Date(parts.join(' '));
}
function parseDate2(string) {
var refStr = new Date().toString();
var fus = Number(refStr.substr(refStr.indexOf('GMT')+4,2));
Logger.log('TZ offset = '+fus);
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
var t = parts[1].split(':');
return new Date(new Date(parts[0]).setHours(+t[0]+fus,+t[1],0));
}
Logger results :
EDIT following first answer
After a small change in the code I managed to get Google's snippet to work but the problem of time zone being lost still remains because of the way JSON converts JS date objects.
new code and logger result below:
function testJSONDate() {
Logger.log('starting value : 2016/3/31 12:00:00');
var jsDate = JSON.stringify(new Date("2016/3/31 12:00:00"));// time is 12:00 I'm in GMT+2
Logger.log('JSON.stringify value : '+jsDate);
Logger.log('JSON parse jsDate : '+JSON.parse(jsDate)); // time is 10:00, UTC
var jsDateWithoutQuotesAndMillisecAndZ = jsDate.replace(/"/g,'').split('.')[0];
Logger.log('jsDateWithoutQuotesAndMillisecAndZ = '+jsDateWithoutQuotesAndMillisecAndZ);
var date = parseDate(jsDateWithoutQuotesAndMillisecAndZ);
Logger.log('parsed RFC3339 date using Google\'s code : '+date); // does not return a valid date
var otherFunction = parseDate2(jsDateWithoutQuotesAndMillisecAndZ);
Logger.log('parsed RFC3339 date using other code : '+otherFunction); // does return a valid date in the right tz
}
You have taken a little helper function out of context. It was only meant as a stopgap device to get the strings returned by a particular API (Google Calendar API) to parse correctly in Apps Script. It is not any kind of universal date converter. A project member threw it together when filing an issue, and a follow-up message in that thread points out another detail that the function doesn't handle.
As of now, the date parser in Apps Script correctly parses the following formats:
function testdate() {
Logger.log(new Date("2016/03/31 10:00:00")); // local time
Logger.log(new Date("2016/03/31 10:00:00 +2:00")); // with given offset
Logger.log(new Date("2016-03-31T08:00:00.000Z")); // in UTC
}
Note that milliseconds are required for UTC timestamp, but are not allowed for the others.
What you do with a datetime string that needs to be parsed but is not one of the above, depends on its format. If you have 2016-03-31T10:00:00 (apparently, this is what Google Calendar API returns) and this is meant to be in local time, then you need exactly what the quoted parse function does: replace T by space and - by /. If the same string represents UTC time, one needs to add .000Z at the end. And so on.