Limit RSS Feed displayed by ZrssFeed by time - javascript

I'm using ZrssFeed to display an rss feed. I would like to limit it to only posts from the last 8 hours.
I tried adding the following block of code after ZRSS returns the feed:
// Add feeds
for (var i=0; i<feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
feedcount = i;
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
var msPerDay = 8*60*60*1000; // 8 hours
var msPubDateTime = new Date(pubdate); // item date in ms
if (msNow.getTime() - entryDate.getTime() < msPerDay) //compare
{
// rest of plugin
This both doesn't work and seems to break the plugin altogether.

You may want to look at the jsDate script. It's great at handling all date-related JS issues.
http://www.datejs.com/

Related

fetch recent email from a specific mail address

I am using the below google apps script to search recent email from a particular mail address in my inbox. This email has no labels and this script is trying to look at all mails. How to minimize the search for an email and pull out the recent one.
function myFunction()
{
var searchterm = 'myemail#mydomain.com';
var threads = GmailApp.search(searchterm);
var messages = GmailApp.getMessagesForThreads(threads);
for (var i = 0; i < threads.length; i++)
{
for (var j = 0; j < messages[i].length; j++)
{
var mailFrom = messages[i][j].getFrom();
}
}
}
How about this sample script?
Modification points :
For var threads = GmailApp.search(searchterm);, threads[0] is the latest thread.
When From is only the particular mail address, it retrieves the mail.
When thread[0] is processed by loop using forEach(), the lower element is newer one.
The script reflected these is as follows.
Script :
var mailAddress = "myemail#mydomain.com";
var mailFrom;
var thread = GmailApp.search("from:" + mailAddress);
thread[0].getMessages().forEach(function(message) {
var f = message.getFrom();
var d = message.getDate();
if (!~f.indexOf(mailAddress)) return;
mailFrom = [f, d];
});
Result :
[name <myemail#mydomain.com>, Sat Jan 1 12:34:56 GMT 2017]
When the process time is measured, I confirmed that this script brought the improvement about 30% for your sample script. Although I don't know whether this is the best, if this is useful for you, I'm glad.
If I misunderstand your question, I'm sorry.
You may use the following search term:
var searchterm = "from: myemail#mydomain.com newer:"+parseInt(date/1000);
where date is the time value of javascript date variable. For example current date can be calculated as:
date = new Date().getTime();
This searchterm would return the email threads that are newer than the above date

Read multiple JSON API Pages and parse data

Objective: To collect JSON data from forecast API and then read the JSON precipIntensity property over the number of days specified, this code starts at three. Since this take a number of steps to coherently follow please try to make sense of all the code.
My main issue is trying to name the JSON code pages that return then put them into another context to read the precipIntensity
property.
To outline: The back date gets the UNIX time, then requests an API for each forecast day. Then the APIs are put in an array. The array is put in a for() loop to request each JSON script... (now what to do? I would like to be able to read each or calculate something but I do not know how to ask for the formatted code. I can do the remaining bit).
A sample of JSON can be found at my other related post...
https://stackoverflow.com/questions/29949454/store-json-api-object-data-and-reuse-it (I found that the API server stores the data for me...solved)
EDITED since 5/1/15:
//Get the back dated times and current in UNIX,
//later make a lookup that gives datediff from current date and user's date and adjust index i condition to equal exact days.
var totalPrecipSinceDate;
var threeDayAPITimes = [];
for (var i = 0; i <= 2; i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //https://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime(); //1318023197289 number of ms since epoch
var unixEpoch = Math.round(epoch/1000)
threeDayAPITimes[i] = Math.round(unixEpoch - (86400 * i));
/*
var epoch = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
threeDayAPITimes[i] = Math.round(epoch - (86400 * i));
*/
}
//Plan to convert UNIX dates to display
//List of locations: LATITUDE,LONGITUDE
var locations = ["46.3494,-85.5083"]
var currentAPIKey ="privateAPIKey"; //gets an APIkey from user from forecaster input.
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time;
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
});
});
//Process result in foreach loop
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (this.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ;
});
}
alert(eachPrecipSum );
Your loop should be something like this:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time;
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
});
}

Preferred Method to (Accurately) Get Time From User Input (in UiApp - GAS)

UiApp has DateBox and DateTimeFormat
for that Class. However, there is no such thing as TimePicker or TimeBox, where a user could enter a time in a well-specified manner such as through using Google Forms:
Forms has different behavior for this Widget in Chrome vs Firefox (I much prefer the Chrome behavior). Anyway, currently I am using a TextBox to get time values, where someone would enter a time value in the following manner:
12:00 or 13:50, etc. These times would be in the 24-hour clock so that I could create new Date objects based on someDate + " " + startTime, which would act as the real start time for an event on the Calendar (this is the process I currently use in several of my applications at work). This is obviously unreliable for several reasons.
Ex: If the user entered anything except a valid 24-hour representation in HH:MM:SS, Date creation would fail.
I don't want to force my boss to be overly-precautious about how he inputs times into the UI, and I also want to avoid regexing "valid" formats and having the UI do a lot of back-end work (it would be 18 regex tests total, and if any failed I'd have to handle them individually).
So, the question: is there an efficient/preferred method of getting times in UiApp, either via TextBox or some other interface?
What about something like that ? Test app here (updated with new version, see edit)
code below :
function doGet() {
var app = UiApp.createApplication().setTitle('enter time');
var frame = app.createVerticalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'15px'});
var handler = app.createServerHandler('setTime').addCallbackElement(frame);
var h = app.createListBox().setId('h').setName('h').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<12;n++){h.addItem(Utilities.formatString('%02d', n),n)}
var m = app.createListBox().setId('m').setName('m').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<60;n++){m.addItem(Utilities.formatString('%02d', n),n)}
var am = app.createListBox().setId('am').setName('am').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
am.addItem('AM').addItem('PM');
var date = app.createDateBox().setValue(new Date()).setFormat(UiApp.DateTimeFormat.DATE_LONG).setName('date').addValueChangeHandler(handler);
var label = app.createHTML('<b>StartTime *</b><br>When your reservation starts').setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'padding-bottom':'10px'});
var subFrame = app.createHorizontalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'5px'});
var result = app.createHTML().setId('date').setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'color':'#AA6','padding-top':'20px'})
.setHTML(Utilities.formatDate(new Date(new Date().setHours(0,0,0,0)), Session.getTimeZone(), 'MMM-dd-yyyy HH:mm'));
frame.add(date).add(label).add(subFrame).add(result);
subFrame.add(h).add(m).add(am);
return app.add(frame);
}
function setTime(e){
var app = UiApp.getActiveApplication();
var date = app.getElementById('date')
var date = new Date(e.parameter.date);
var am = e.parameter.am
if(am=='AM'){am=0}else{am=12};
var h = Number(e.parameter.h)+am;
var m = Number(e.parameter.m);
date.setHours(h,m,0,0)
Logger.log(date);
app.getElementById('date').setHTML(Utilities.formatDate(date, Session.getTimeZone(), 'MMM-dd-yyyy HH:mm'));
return app
}
EDIT : here is the wrapped version and a demo with a grid and 10 panels.
function doGet() {
var app = UiApp.createApplication().setTitle('enter time');
var grid = app.createGrid(10,2)
var handler = app.createServerHandler('setTime').addCallbackElement(grid);
var varName = 'date';
var htmlString = '<b>StartTime *</b> When your reservation starts'
for(var idx=0 ; idx<10;idx++){
var frame = pickDate(idx,varName,htmlString,handler);
grid.setText(idx, 0, 'test widget '+idx+' in a grid').setWidget(idx,1,frame);
}
var result = app.createHTML('<h1>Click any widget</h1>').setId('result');
return app.add(grid).add(result);
}
/* wrapped version
** takes a var name + index + label string + handler
** as input parameter
** The same handler will be used for every occurrence , the source being identified in the handler function (see code example below)
** and returns a selfcontained widget that you can add to a panel or assign to a grid
** or a flex Table
*/
function pickDate(idx,varName,htmlString,handler){
var app = UiApp.getActiveApplication();
var frame = app.createVerticalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'1px', 'border-radius':'5px'});
var h = app.createListBox().setId('h'+idx).setName('h'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<12;n++){h.addItem(Utilities.formatString('%02d', n),n)}
var m = app.createListBox().setId('m'+idx).setName('m'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<60;n++){m.addItem(Utilities.formatString('%02d', n),n)}
var am = app.createListBox().setId('am'+idx).setName('am'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
am.addItem('AM').addItem('PM');
var date = app.createDateBox().setValue(new Date()).setFormat(UiApp.DateTimeFormat.DATE_LONG).setId(varName+idx).setName(varName+idx).addValueChangeHandler(handler);
var label = app.createHTML(htmlString).setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'padding-bottom':'3px'}).setId('html'+idx);
var subFrame = app.createHorizontalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFE','padding':'1px', 'border-radius':'4px'});
frame.add(label).add(date).add(subFrame);
subFrame.add(h).add(m).add(am);
return frame;
}
function setTime(e){
// Logger.log(JSON.stringify(e));
var app = UiApp.getActiveApplication();
var idx = Number(e.parameter.source.replace(/\D+/,''));
Logger.log('date'+idx+ ' > '+e.parameter['date'+idx]);
var date = new Date(e.parameter['date'+idx]);
var am = e.parameter['am'+idx];
if(am=='AM'){am=0}else{am=12};
var h = Number(e.parameter['h'+idx])+am;
var m = Number(e.parameter['m'+idx]);
date.setHours(h,m,0,0)
app.getElementById('result').setHTML('<h1>Widget Nr '+idx+' has value '+Utilities.formatDate(date, Session.getTimeZone(), 'MMM-dd-yyyy HH:mm')+'</h1>');
return app
}

Twitter API: Count number of Tweets since 0:00am this morning?

Is there an API to count the number of Tweets since 0:00am this morning for a particular user? I have tried the following Javascript but the closest I can get to it is the total number of tweets for all time for that user.
$.getJSON("http://api.twitter.com/1/statuses/user_timeline/BarackObama.json?count=1&include_rts=1&callback=?", function(data) {
$("#twitter").html(data[0].user.statuses_count);
});
You can download the user timeline until you get tweets which were posted "yesterday" (i.e. before 0:00am). Once you get it, you just have to count tweets which were posted "today" (i.e. after 0:00am).
EDIT 1 : a pseudo JavaScript code for getting it
var howManyTweetsWerePostedToday = function () {
var timeline = downloadTimeline()
var lastTweet = timeline[timeline.length-1]
var now = new Date()
var today = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDay(), 0, 0, 0, 0) // Limit between today and yesterday
var lastTweetDate = new Date(lastTweet["created_at"])
while (lastTweetDate.getTime() >= today.getTime()) {
var lastTweetID = lastTweet["id_str"]
var earlierTweetsTimeline = downloadTimeline(max_id = lastTweetID)
timeline = timeline.concat(earlierTweetsTimeline.shift())
lastTweet = timeline[timeline.length-1]
lastTweetDate = new Date(lastTweet["created_at"])
}
return getNumberOfTweetsThatWerePostedTodayInTheTimeline(timeline)
}();
With downloadTimeline() which is a function calling the GET statuses/user_timelineTwitter API endpoint to get the timeline. See https://dev.twitter.com/docs/api/1/get/statuses/user_timeline for details about the endpoint, especially max_id which is the highest tweet ID that will be in the results.
created_at is the date when a tweet was posted. id_str is the ID of a tweet under a String form. See https://dev.twitter.com/docs/platform-objects/tweets for more details about tweets.

Fetching timestamps (hh:mm:ss) from Youtube comments with Youtube API using regex in JavaScript

I am analyzing timestamped YouTube comments. Because some comments may refer to a period in either mm:ss, m:ss, hh:mm:ss, or h:mm:ss, I need to prepare for these cases. The following code works on mm:ss and m:ss, but still treats the one with hours as if it was mm:ss. For example, 02:24:30 returns 144, as it is only analyzing the first two parts. Here is the code:
var timePattern = /(([0-5][0-9])|[0-9])\:[0-9]{2,2}/;
var seconds = "";
for (var i = 0; i < comments.length; i++) {
var matches = comments[i].match(timePattern);
var matched = matches[0];
var a = matched.split(':');
if(matched.length == 7 || matched.length == 8) {
seconds = (+a[0])*60*60 + (+a[1])*60 + a[2];
} else {
seconds = (+a[0])*60 + (+a[1]);
}
times.push(seconds);
}
Try a different regex.
(?:([0-5]?[0-9]):)?([0-5]?[0-9]):([0-5][0-9])
First contains hours, second contains minutes, last contains seconds.
Hours will be empty if no hours are found.
You can also get this info on the comments feed, if you're using the API: https://developers.google.com/youtube/2.0/developers_guide_protocol#Comments
The comments feed have a published element that contains the date and time information that you can use to parse the seconds of.

Categories