Today is my first day using Google Apps Script. I am trying to make a script to grab weather information from the Wunderground Api and paste it into a spreadsheet.
For some reason I am getting the error message "Missing ';' before statement. (Line 34)".
I've searched for a solution but cant find why I am getting this error in my code.
//Everyday this script gets weather data from Weather Underground and records it in this spreadsheet.
cDay = 0, cTemp = 1, cHumidity = 2, cPressure=3, cSparkline=4, cConditions=5;
nCols=7;
function getTemp() {
var url = 'http://api.wunderground.com/api/' + appKey + '/conditions/q/CO/Aspen.json';
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var response = UrlFetchApp.fetch(url);
var contentText = response.getContentText();
var conditions = Utilities.jsonParse(contentText);
var todaysConditions = conditions;
var temp = todaysConditions.current_observation.temp_c;
var humidity = todaysConditions.current_observation.relative_humidity;
var pressure = todaysConditions.current_observation.pressure_in;
var conditions = todaysConditions.response.features.conditions;
sheet.insertRowAfter(1);
var range = sheet.getRange(2,1,1, nCols);
var row = range.getValues()[0];
var d = new Date;
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
var hour = d.getHours() + 1;
var minutes = d.getMinutes();
row[cDay] = month + '/' + day + '/' + year + '' + hour + ':' minutes; //here is the error
row[cTemp] = temp;
row[cHumidity] = humidity;
row[cPressure] = pressure;
row[cConditions] = conditions;
var nRows = numRows >= 10 ? 10 : numRows;
//row[cSparkline] = "=SPARKLINE(R[0]C[-3]:R[" + (nRows-1) + "]C[-3])";
range.setValues([row]);
}
Any help is appreciated
You have missed the '+' sign
row[cDay] = month + '/' + day + '/' + year + '' + hour + ':' + minutes;
Related
I found a lot of useful stuff in this forum. I am new to GAS and JS coding in general and I cannot find a way to solve something that I am confident it's NBD.
I am attaching the code first:
function emailAlert() {
// today's date information
var today = new Date();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
var todayYear = today.getFullYear();
// getting data from spreadsheet
var url = SpreadsheetApp.getActiveSpreadsheet().getUrl();
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("Assignments");
var resultssn = SpreadsheetApp.openByUrl(url).getName();
//Emails addresses
var emailJonDoe = "example#example.com"
var emailEmilyDoe = "example#example.com"
var duedatesRange = sheet.getRange("H5:H9");
var duedates = duedatesRange.getValues();
var actionitRange = sheet.getRange("C5:C9");
var actionit = actionitRange.getValues();
var prjsRange = sheet.getRange("B5:B9");
var prjs = prjsRange.getValues();
var whosRange = sheet.getRange("D5:D9");
var whos = actionitRange.getValues();
//looping through all of the rows
for (var i = 0; i < duedates.length; ++i) {
var row = duedates[i];
for (var i = 0; i < actionit.length; ++i) {
var assignmenttext = actionit[i];
for (var i = 0; i < prjs.length; ++i) {
var project = prjs[i];
for (var i = 0; i < whos.length; ++i) {
var user = whos[i];
var expireDateFormat = Utilities.formatDate(
new Date(row[i]),
'ET',
'MM/dd/yyyy'
);
// email information
var subject = '';
var message =
" One of your action items is due today. " +
'\n' +
'\n' +
' Project: ' +
project[i] +
'\n' +
'\n' +
' Action Item: ' +
assignmenttext[i] +
'\n' +
'\n' +
'Check the Tracker now !!' +
'\n' +
url;
//expiration date information
var expireDateMonth = new Date(row[i]).getMonth() + 1;
var expireDateDay = new Date(row[i]).getDate();
Logger.log("Expire date is:" + expireDateDay);
//check for JD and send email to him if true
if (
user[i] === "JD" &&
expireDateMonth === todayMonth &&
expireDateDay === todayDay
) {
var subject =
'FEG AAAAAAManagement - An action item is due today!! : ' + assignmenttext[i];
MailApp.sendEmail(emailJonDoe, subject, message);
Logger.log('todayyyy!');
}
//check for ED and send email to him if true
if (
user[i] === "ED" &&
expireDateMonth === todayMonth &&
expireDateDay === todayDay
) {
var subject =
'FEG DDDDDManagement - An action item is due today!! : ' + assignmenttext[i];
MailApp.sendEmail(emailEmilyDoe, subject, message);
Logger.log('todayyyy!');
}
}
}
}
}
}
enter image description here
This is a simple snippet that send emails for each row that contains today's date in column H.
I have a similar one already working but I would like to implement the "user" feature.
Long story short, I want the code to:
Check for for each row that contains today's date in column H.
For each of above rows, check the content of it's respective cell in column D.
If it contains JD, send email alert to JD's email. If it contains ED, send email alert to ED's email.
The email should contain row's respective cell for column C (assignmenttext) and column B (project).
AFAIK, this code is not too heavy on the server side since I only "getRange" at the beginning and most of the code runs on the client side (is this correct?).
I am not confident with which loop function to use in this case and how to implement it with my code.
I am open to any comment or suggestion. Thanks in advance to anyone who would spend some time to help me. (:
This is the sort of thing I would have done. Admittedly you have to be comfortable with dealing with arrays but it makes for a nice compact code.
The two objects emails and prefix provide a place to enter new users all in one place and simplify the code by allow you to use a single send command.
function emailAlert() {
const sentcolumn=45;//I recommend adding some column to contain and indication of when an email is already been sent.
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName("Assignments");
const vA=sh.getRange(5,1,5,sentcolumn).getValues();//your data went from row 5 to row 9 that is five rows
const dt=new Date();
const today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//this is a number
const emails={"JD":"jd#example.com","ED":"ed#example.com"};//emails
const prefix={"JD":"FEG AAAAAAManagement - An action item is due today!! : ","ED":"FEG DDDDDManagement - An action item is due today!! : "};//subject prefixes
vA.forEach(function(r,i){
let x=new Date(r[7]);
let duedate=new Date(x.getFullYear(),x.getMonth()+1,x.getDate()).valufOf();//this is a number
var body=Utilities.formatString('One of your action items is due today. \n\n Project: %s \n\n Action Item: %s\n\nCheck the Tracker now !!\n%s',r[1],R[2],ss.getUrl());
let subject=prefix[r[3]] + r[2];
if(today==duedate && r[sentcolumn-1]!='Sent') {
GmailApp.sendEmail(emails[r[3]],subject,body);
sh.getRange(i+5,sentcolumn).setValue('Sent');//adding something like this would keep you from sending duplicate emails by mistake
}
});
}
This could be done using a single for loop, checking data in each row:
function sendEmail() {
// today's date information
var today = new Date();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
var todayYear = today.getFullYear();
Logger.log(todayDay);
// getting data from spreadsheet
var url = SpreadsheetApp.getActiveSpreadsheet().getUrl();
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("Assignments");
var resultssn = SpreadsheetApp.openByUrl(url).getName();
//Emails addresses
var emailJonDoe = "example#example.com"
var emailEmilyDoe = "example#example.com"
var lastRow = sheet.getLastRow();
var dataRange = sheet.getRange(2,1,lastRow,8).getValues();
//looping through all of the rows
for (var i = 0; i < lastRow-1; i++) {
var project = dataRange[i][1];
var assignmenttext = dataRange[i][2];
var user = dataRange[i][3];
var row = dataRange[i][7];
//expiration date information
var expireDateFormat = Utilities.formatDate(new Date(row),'ET','MM/dd/yyyy');
var expireDateMonth = new Date(row).getMonth() + 1;
var expireDateDay = new Date(row).getDate();
Logger.log("Expire date is:" + expireDateDay);
//check for expiry date
if (expireDateMonth === todayMonth && expireDateDay === todayDay) {
var subject =
'FEG AAAAAAManagement - An action item is due today!! : ' + assignmenttext;
// email information
var message =
" One of your action items is due today. " +
'\n' +
'\n' +
' Project: ' +
project +
'\n' +
'\n' +
' Action Item: ' +
assignmenttext +
'\n' +
'\n' +
'Check the Tracker now !!' +
'\n' +
url;
if (user === 'JD') {
MailApp.sendEmail(emailJonDoe, subject, message);
}
if (user === 'ED') {
MailApp.sendEmail(emailEmilyDoe, subject, message);
}
}
}
}
Running this on a sample sheet returns:
Note that I did not send emails, instead I just logged values in my test code.
Iam working in cordova with cordova-local-notifications plugin. First the clear function was working but now when I clear and restart the application the notification all show up...
This is my clear function:
$('.clearbtn').click(function(){
var arraylength = info.data;
arraylength.splice(0,arraylength.length);
console.log('clear',arraylength);
});
The console log shows me that the array has nothing inside it. And this is the outcome of the console.log(info.data)
and this is the all reminder page:
$(document).on("pagebeforeshow","#all",function(){
var html = '';
for(var count = 0; count < info.data.length; count++){
console.log(info.data);
var time = new Date(info.data[count][3]);
var addHour = time.setHours(time.getHours());
var date = new Date(addHour);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2);
var imgPath = 'img/icons/alert.png';
html = html + "<tr><td class='img-table'><img src=" + imgPath + "></td>" + "<td><span class='time-aside'><strong>" + formattedTime + "</strong></span><h4>" + info.data[count][1] + "</h4><p>" + info.data[count][2] + "</p></td></tr>";
}
$('.clearbtn').click(function(){
var arraylength = info.data;
arraylength.splice(0,arraylength.length);
console.log('clear',arraylength);
});
$("table#notificationTable tbody").empty();
$("table#notificationTable tbody").append(html).closest("table#notificationTable").table("refresh").trigger("create");
});
I really don't get it because it was working before but I don't know why its not anymore!
I had to clear localStorage aswell.. Because I push it to localstorage as string. Here is a rewrite of the function:
$('.clearbtn').click(function(){
var arraylength = info.data;
arraylength = 0;
localStorage.clear();
});
I have the following javascript that prints the timestamp:
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(hours + "" + minutes + seconds + month + "" + day + "" + year)
//-->
</script>
However I want to use this timestamp in many places in the page, how can i call it like $timestamp so i can control where its placed?
Thanks in advance.
Set a variable, like:
var timestamp = hours + "" + minutes + seconds + month + "" + day + "" + year;
and later in code use that variable to show info in your page, like:
var container = document.getElementById('container1');
container.innerHTML = timestamp;
where 'container1' is a html element like span, div, p, etc. ex:
<span id="container1"></span>
answer
<script>
function startTime()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<span id="txt"></span>
<script type="text/javascript">
startTime().swap('txt');
</script>
How can I modify this script to encase the AM/PM text in a div?
I already tried modifying the areas where it outputs the ampm with a div, but it didnt put the element in a div, instead displaying the and tags as plaintext.
function myTime() {
var dst = 0; // set to 1 for daylight savings time
// update this as you go on and off daylight saving time
var loc = ''; // set to your location
var mtz = -5; // set to your local timezone (hours ahead of UTC, negative if behind)
var stdz = ''; // standard time indicator
var dayz = ''; // daylight saving time indicator (blank if you dont have daylight saving)
var showDate = 0; // 0 = don't show, 1 = international format, 2 = US format
// do not alter anything below this line
var newP = document.createElement("div"); var txt = '' + loc + ' '; var newT = document.createTextNode(txt); newP.appendChild(newT); var newP2 = document.createElement("div"); newP2.id = 'time'; var txt2 = setDsp(mtz,dst,stdz,dayz,showDate); var newT2 = document.createTextNode(txt2); newP2.appendChild(newT2); var frag = document.createDocumentFragment(); frag.appendChild(newP); frag.appendChild(newP2); var d2 = document.getElementById('datetime'); d2.parentNode.replaceChild(frag,d2);
setTimeout('updDsp('+mtz+',' +dst+',"' +stdz+'","' +dayz+'","'+showDate+'")', 5000);}
var pageLoaded = 0; window.onload = function() {pageLoaded = 1;}
function loaded(i,f) {if (document.getElementById && document.getElementById(i) != null) f(); else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
function updDsp(mtz,dst,stdz,dayz,showDate) {var obj = document.getElementById('time'); obj.firstChild.data = setDsp(mtz,dst,stdz,dayz,showDate); setTimeout('updDsp('+mtz+ ','+dst+ ',"'+stdz+ '","'+dayz+ '","'+showDate+'")', 5000);}
function setDsp(mtz,dst,stdz,dayz,showDate) {var dayname = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday']; var month = ['January','February','March','April','May','June','July','August','September','October','November','December']; var now = new Date; now.setUTCMinutes(now.getUTCMinutes() + (mtz + dst)*60); var dow = now.getUTCDay(); var minute = now.getUTCMinutes();
var hour = now.getUTCHours(); if (hour > 11) {ampm = 'PM'; hour -= 12;} else {ampm = 'AM'} if (hour == 0) {hour = 12;} if (minute < 10) {pad = ':0';} else {pad = ':';} var txt = hour + pad + minute + ' ' + '' + ampm + ''; if (dst) txt += dayz; else txt += stdz; txt += ' '
if (showDate == 1) txt += ' ' + now.getUTCDate() + ' ' + month[now.getUTCMonth()] + ', ' + now.getUTCFullYear();
if (showDate == 2) txt += ' ' + month[now.getUTCMonth()] +' ' + now.getUTCDate() + ', ' + now.getUTCFullYear();
return (txt);
}
loaded('datetime',myTime);
Your code is way over complex. I'd suggest replacing the myTime() function with this that just builds HTML rather than create all the various text nodes. This also puts the AM or PM designation in a <span class="ampm"> so it can be styled appropriately:
function myTime() {
var dst = 0; // set to 1 for daylight savings time
// update this as you go on and off daylight saving time
var loc = ''; // set to your location
var mtz = -5; // set to your local timezone (hours ahead of UTC, negative if behind)
var stdz = ''; // standard time indicator
var dayz = ''; // daylight saving time indicator (blank if you dont have daylight saving)
var showDate = 0; // 0 = don't show, 1 = international format, 2 = US format
var timeStr = setDsp(mtz, dst, stdz, dayz, showDate);
timeStr = timeStr.replace(/AM|PM/i, '<span class="ampm">$&</span>');
var d = document.getElementById('datetime');
d.innerHTML = '<div id="time">' + loc + " " + timeStr + '</div>';
setTimeout(myTime, 500);
}
And here's a working version: http://jsfiddle.net/jfriend00/jTbf2/
I am calculating on date part through java script , but it is giving NAN-NAN-NAN in Firefox and chrome while working fine in IE . My code is below which is i am using.
var datedisp = $("#txtDateinputBox_startdate").val();
datedisp = datedisp.split("/");
var month = datedisp[0];
var year = datedisp[2];
var dtepart = eval(datedisp[1]);
var moddate = dtepart + SetID - 1;
var finaldate = month + '-' + moddate + '-' + year;
var disp_fdate = new Date(finaldate);
//alert(finaldate);
var disp_date = disp_fdate.getDate();
//var disp_date = disp_fdate.getUTCFullDate();
var disp_month = disp_fdate.getMonth() + 1;
var disp_year = disp_fdate.getYear();
var uidate = eval(disp_month) + '-' +eval( disp_date) + '-' + eval(disp_year);
and then this uidate is using in div creation.
Please Help
Thanks In Advance
This?
var date, i, string;
function date_to_string( date ) {
return ( date.getMonth() + 1 ) + '-' + date.getDate() + '-' + date.getFullYear();
}
date = new Date( '01/27/2012' );
for ( i = 0; i < 14; i += 1 ) {
date.setDate( date.getDate() + 1 );
string = date_to_string( date );
// use string
}
Live demo: http://jsfiddle.net/ekaDg/