How can I write the following script so that it picks up the local current time rather than me having to input the date each day? Note July 1 is the correct start date it's the second date that I have to change each time, as I'm importing a range of data from Gcal to Gsheets to review.
function export_gcal_to_gsheet() {
var mycal = "email";
var cal = CalendarApp.getCalendarById(mycal);
var events = cal.getEvents(new Date("July 01, 2022 00:00:00 UTC"), new Date ("September 15, 2022 23:59:59 UTC"));
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
var header = [["Calendar Address", "Event Title", "Event Description", "Event Location", "Event Start", "Event End", "Calculated Duration", "Visibility", "Date Created", "Last Updated", "MyStatus", "Created By", "All Day Event", "Recurring Event"]]
var range = sheet.getRange(6, 1, 1, 14);
range.setValues(header);
for (var i = 0; i < events.length; i++) {
var row = events.length + 6 - i;
var myformula_placeholder = '';
var details=[[mycal,events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), events[i].getStartTime(), events[i].getEndTime(), myformula_placeholder, ('' + events[i].getVisibility()), events[i].getDateCreated(), events[i].getLastUpdated(), events[i].getMyStatus(), events[i].getCreators(), events[i].isAllDayEvent(), events[i].isRecurringEvent()]];
var range=sheet.getRange(row,1,1,14);
range.setValues(details);
var cell=sheet.getRange(row,7);
cell.setFormula('=(HOUR(F' +row+ ')+(MINUTE(F' +row+ ')/60))-(HOUR(E' +row+ ')+(MINUTE(E' +row+ ')/60))');
cell.setNumberFormat('.00');
}
}
I wasn't able to get it to do local time but I brought in the following for today;
I replaced the second "(new Date("July 01, 2022 00:00:00 UTC")" with "new Date ());"
So now I have;
function export_gcal_to_gsheet() {
var mycal = "Email";
var cal = CalendarApp.getCalendarById(mycal);
var events = cal.getEvents(new Date("July 01, 2022 00:00:00 UTC"), new Date ());
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
var header = [["Calendar Address", "Event Title", "Event Description", "Event Location", "Event Start", "Event End", "Calculated Duration", "Visibility", "Date Created", "Last Updated", "MyStatus", "Created By", "All Day Event", "Recurring Event"]]
var range = sheet.getRange(6, 1, 1, 14);
range.setValues(header);
for (var i = 0; i < events.length; i++) {
var row = events.length + 6 - i;
var myformula_placeholder = '';
var details=[[mycal,events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), events[i].getStartTime(), events[i].getEndTime(), myformula_placeholder, ('' + events[i].getVisibility()), events[i].getDateCreated(), events[i].getLastUpdated(), events[i].getMyStatus(), events[i].getCreators(), events[i].isAllDayEvent(), events[i].isRecurringEvent()]];
var range=sheet.getRange(row,1,1,14);
range.setValues(details);
var cell=sheet.getRange(row,7);
cell.setFormula('=(HOUR(F' +row+ ')+(MINUTE(F' +row+ ')/60))-(HOUR(E' +row+ ')+(MINUTE(E' +row+ ')/60))');
cell.setNumberFormat('.00');
}
}
Seems to work pretty well - set up a trigger every time my calendar is updated to run this script and it brings everything over up to the current date automatically - works really well - only posting as I thought others might use it.
Related
I am including the script ( below), the trigger, the sample of the spreadsheet, image of the start and end time formatting and the error(below)...
When I run the createCalendarEvent script manually...no issues..it is when i try to automate the script by creating an event trigger for on form submit that I get the following error:
Error Exception: Event start time must be before event end time.
at createCalendarEvent(create event:26:16)
function createCalendarEvent() {
var sheet = SpreadsheetApp.getActiveSheet();
var calendar =
CalendarApp.getCalendarById("c_71lju3i096qeqsg69bd7togo9g#group.calendar.google.com");
var startRow = 2; // First row of data to process - 2 exempts my header row
var numRows = sheet.getLastRow(); // Number of rows to process
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows-1, numColumns);
var data = dataRange.getValues();
var complete = "Done";
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var startTime = new Date(row[0]); //start Time
var endTime = new Date(row[1]); //end Time
var title = row[2]; //Item Title
var option = row[3]; //event option
var location = row[4]; //location
var eventID = row[6]; //event marked Done
if (eventID != complete) {
var currentCell = sheet.getRange(startRow + i, numColumns);
calendar.createEvent(title, startTime, endTime, {description: option + '\r' , location:
location});
currentCell.setValue(complete);
}
}
}
I have edited the original script and included the trigger just in the script itself ( By passing the automated trigger creation)...this way worked....1 time!..now i get the following error.
Exception: Action not allowed setUpTrigger # create event.gs5
function setUpTrigger() {
ScriptApp.newTrigger('createCalendarEvent')
.forForm('1FAIpQLScQvxc8EUSjGvrrVc6-QE3LwNZOytetIrfOVX-RKrJwS8_ALw')
.onFormSubmit()
.create();
}
function createCalendarEvent() {
var sheet = SpreadsheetApp.getActiveSheet();
var calendar = CalendarApp.getCalendarById("c_71lju3i096qeqsg69bd7togo9g#group.calendar.google.com");
var startRow = 2; // First row of data to process - 2 exempts my
header row
var numRows = sheet.getLastRow(); // Number of rows to process
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows-1, numColumns);
var data = dataRange.getValues();
var complete = "Done";
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var startTime = new Date(row[0]); //start Time
var endTime = new Date(row[1]); //end Time
var title = row[2]; //Item Title
var option = row[3]; //event option
var location = row[4]; //location
var eventID = row[6]; //event marked Done
if (eventID != complete) {
var currentCell = sheet.getRange(startRow + i, numColumns);
calendar.createEvent(title, startTime, endTime, {description:
option + '\r' , location: location});
currentCell.setValue(complete);
}
}
}
The error message is pretty self explanatory.
Error Exception: Event start time must be before event end time
Check the values you are sending for start and end time. Make sure that the event does not end before it starts.
var startTime = new Date(row[0]); //start Time
var endTime = new Date(row[1]); //end Time
I just attach my woocommerce through webhook in google sheet and get some code from internet for getting orders data on it every things looks fine but there is only one product name available even if the order contain more than one products.You can check the webhook data here when order is created. here is my google sheet script code
//this is a function that fires when the webapp receives a GET request
function doGet(e) {
return HtmlService.createHtmlOutput("request received");
}
//this is a function that fires when the webapp receives a POST request
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var order_created = myData.date_created;
var product_name = myData.line_items[0].name;
var itemName = myData.line_items[0].name;
var quantity = myData.line_items[0].quantity;
var product_items = quantity + " x " + itemName + "\n";
var product_qty = myData.line_items[0].quantity;
var order_total = myData.total;
var billing_email = myData.billing.email;
var billing_first_name = myData.billing.first_name;
var billing_phone = myData.billing.phone;
var shipping_address = myData.shipping.address_1;
var timestamp = new Date();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp,order_created,billing_first_name,billing_phone,shipping_address,product_name,product_qty,order_total,billing_email,product_items]);
}
You are trying to loop through sone JSON transaction data that includes multiple line items.
There are two flaws in your code:
1 - the script does not loop through the product items:
var product_name = myData.line_items[0].name;
var itemName = myData.line_items[0].name;
var quantity = myData.line_items[0].quantity;
var product_items = quantity + " x " + itemName + "\n";
var product_qty = myData.line_items[0].quantity;
You are getting line_items[0], but if there are multiple line items in the transaction then you are only ever returning the first line item.
2 - The variables being appended in sheet.appendRow() need to be re-considered.
Your code specifies ten variables, including product name and product quantity. However there are no unique values for these two variables since they are form part of the line items and vary with each line item in the transaction.
Your variable product_items is an attempt to recognise this by concatenating the details for each line item; however the variable fails because it depends on looping through the line_items AND progressively concatenating line item values.
The following code is an example of how you might achieve your outcome:
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var timestamp = new Date();
var order_created = myData.date_created;
var billing_first_name = myData.billing.first_name;
var billing_phone = myData.billing.phone;
var billing_email = myData.billing.email;
var shipping_address = myData.shipping.address_1;
var order_total = myData.total;
var lineitems=""
for (i in myData.line_items)
{
var product_name = myData.line_items[i].name;
var itemName = myData.line_items[i].name;
var quantity = myData.line_items[i].quantity;
var linetotal = myData.line_items[i].total;
var product_items = quantity + " x " + itemName + ":$"+linetotal +"\n";
var lineitems =lineitems+product_items;
}
Logger.log("Timestamp: "+timestamp);
Logger.log("Order created: "+order_created);
Logger.log("Billing first name: "+billing_first_name+", Phone: "+billing_phone+", Email: "+billing_email);
Logger.log("Shipping Address: "+shipping_address)
Logger.log("Line items = "+lineitems);
Logger.log("Order Total: "+order_total)
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp,order_created,billing_first_name,billing_phone,shipping_address,order_total,billing_email,lineitems]);
}
I have no experience with script writing, but I was able to find a script and edit it (with lots of trial and error) to fit my need.
I have a Google Form where the first question allows users to select a date, but it is not necessarily the date users are completing the form. The results export to a Google Sheet, and I have a script that sends an email with the form responses.
It worked beautifully until Daylight Savings Time. Now, the dates in the spreadsheet are correct, but in the emails they are one day off.
Example email message:
Your child, NAME, received a dress code violation on Wed Mar 27 2019
23:00:00 GMT-0600 (CST), for No ID.
Before Daylight Savings Time, the time was showing as 00:00:00.
In the code, row[2] is the date pulled from the spreadsheet.
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Script");
var startRow = 2;
var numRows = 5000;
var dataRange = sheet.getRange(startRow, 1, numRows, 5000)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[12];
var message = "Your child, " + row[10] + ", received a dress code violation on " + row[2] + ", for " + row[11] + ".\nIf you have any questions, please email NAME at name.name#name.org\n\nThank you,\n\nNAME\nAssistant Principal";
var emailSent = row[13];
if (emailSent != EMAIL_SENT) {
var subject = "Uniform Violation - Do Not Reply";
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 14).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
Ideally, the email would provide the date exactly from the spreadsheet in MM/DD/YYYY format.
Instead, the emails show the previous day with the time of 11 pm.
Try this:
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var ss=SpreadsheetApp.getActive();//added this
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Script");
var startRow = 2;
var numRows = 5000;
var dataRange = sheet.getRange(startRow, 1, numRows, 5000)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[12];
var message = "Your child, " + row[10] + ", received a dress code violation on " + Utilities.formatDate(new Date(row[2]),ss.getSpreadsheetTimeZone(), "MM dd, yyyy HH:mm:ss" ) + ", for " + row[11] + ".\nIf you have any questions, please email NAME at name.name#name.org\n\nThank you,\n\nNAME\nAssistant Principal";//modified this
var emailSent = row[13];
if (emailSent != EMAIL_SENT) {
var subject = "Uniform Violation - Do Not Reply";
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 14).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
You will probably have to change the dates format.
Date Format
I use Full Calendar in my project and I need to get year and month when I click on Prev or Next button.
This is my code, but doesn't work !! It return alway the current date.
$('body').on('click', 'button.fc-prev-button', function () {
var tglCurrent = $('#calendar').fullCalendar('getDate');
var year = moment(tglCurrent).format('YYYY');
var month = moment(tglCurrent).format('MM');
alert('Year is '+year+' Month is '+month);
});
$('body').on('click', 'button.fc-next-button', function () {
var tglCurrent = $('#calendar').fullCalendar('getDate');
var year = moment(tglCurrent).format('YYYY');
var month = moment(tglCurrent).format('MM');
alert('Year is ' + year + ' Month is ' + month);
});
How can I resolve this issue ?
Try to do it in below way
$('body').on('click', 'button.fc-prev-button', function () {
var tglCurrent = $('#calendar').fullCalendar('getDate');
var date = new Date(tglCurrent);
var year = date.getYear();
var month = date.getMonth();
alert('Year is '+year+' Month is '+month);
});
i have a drop down "Weeks". by default i want it to show the current week. i have tried using this
for (int i = 1; i <= 5; i++)
{
ddlWeek.SelectedValue = ((DateTime.Now.Day + 6 / 7 ).ToString());
}
but the problem is from "29/12/14 - 31/12/14" it is showing week 5. but when its "1/1/15" it is showing week 1 which i think is quite incorrect. my expected result is
29/12/14 - 4/1/15 = "week 5",
5/1/15 - 11/1/15 = "week 1",
12/1/15 - 18/1/15 = "week 2",
19/1/15 - 25/1/15 = "week 3",
26/1/15 - 1/2/15 = "week 4",
2/2/15 - 8/2/15 = "week 1"
and so on. how to i do so that the result appear like this??
this code maybe can help you:
I modify the code in the response of this post:
Get a list of weeks for a year - with dates
You only need a DropDownList called DropDownList1 and paste the code in Page_Load event to test it.
var jan1 = new DateTime(DateTime.Today.Year, 1, 1);
var startOfFirstWeek = jan1.AddDays(1 - (int)(jan1.DayOfWeek));
var weeks =
Enumerable
.Range(0, 54)
.Select(i => new
{
weekStart = startOfFirstWeek.AddDays(i * 7)
})
.TakeWhile(x => x.weekStart.Year <= jan1.Year)
.Select(x => new
{
x.weekStart,
weekFinish = x.weekStart.AddDays(6)
})
.SkipWhile(x => x.weekFinish < jan1.AddDays(1))
.Select((x, i) => new
{
x.weekStart,
x.weekFinish,
weekNum = i + 1
});
//After get weeks' information, manipulate it to get the results.
DateTime Today = Convert.ToDateTime(DateTime.Now.Date.ToShortDateString()); //Convert to ShortDate to delete the HH:mm:ss
string lblItem = "";
foreach (var X in weeks)
{
//Check the Month and the Year must be from the actual Month
if (X.weekStart.Month == Today.Month || X.weekFinish.Month == Today.Month && X.weekFinish.Year == Today.Year)
{
lblItem = "#" + X.weekNum + " " + X.weekStart.ToShortDateString() + " - " + X.weekFinish.ToShortDateString();
DropDownList1.Items.Add(lblItem); //Add item in DropDownList
if (Today >= X.weekStart && Today <= X.weekFinish) //Check if the current date is between the week
DropDownList1.SelectedValue = lblItem; //Select the current week
}
}
if you want to add the items with values manually, you can do this. And then compare the items with the current date, as i do in the code.
Hope this help.