google apps script convert string to object - google-apps-script

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);

Related

APP-SCRIPT Condition to check if date entered is before today's date

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

Google App Script Card Service datepicker returns strange value

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");

Converting Unix timestamp in Google App scripts

I am new to Google App Script and am currently working on a project to help myself get familiar with it. My project has a part where I have to convert Unix Timestamp objects in nested JSON to human-readable time. As I don't know about converting timestamps in Google App scripts, I looked into the documentation and found "Utilities.formatDate()".
I tried using it on an example timestamp to see how it works and if it can be used for my needs. So I took a timestamp from the data and tried converting it with this code.
function blah () {
var tim = "1572401067";
var formattedDate = Utilities.formatDate(tim, "GMT+5:30", "MM-dd-yyyy HH:mm:ss");
Logger.log(formattedDate);
}
It ends with an error saying:
Cannot find method formatDate(string,string,string). (line 3, file "Code")Dismiss
What am I doing wrong here?
As your error message correctly describes, there is no such function as formatDate(string,string,string). The formatDate function that exists in GAS takes three parameters, where the first one is a Date, and the second and third ones are string's. A correction of your code could look like the following:
function blah() {
var tim = 1572401067;
var date = new Date(tim*1000);
var formattedDate = Utilities.formatDate(date, "GMT+5:30", "MM-dd-yyyy HH:mm:ss");
Logger.log(formattedDate);
}

Date format issue, google apps script

I have a column contain a date in "Sep -13" format.
When I access it from code, it gives integer value. How can I get a date object?
If I use "dd/mm/yyyy" format in sheet, it gives me date object.
function check()
{
var source = SpreadsheetApp.openById('sheet id');
var sourcesheet = source.getSheetByName('sheet name');
var tt = sourcesheet.getRange('F700').getValue();
debugger;
}
Result:
That cells original value might be an integer. That could be happen if you copy and paste values only for a date. so .getValue() will give you that number.
You can use that number to create a date object. JavaScript dates can be constructed by passing milliseconds
//base date 01/01/1970 integer value :25569
//excelDate your date in integer
var myDate = new Date((excelDate - 25569)*86400*1000);

Insert a DatePicker

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').