How to Format fb.created_time - javascript

I am new to javascript and I used the tutorial found here: http://www.prettyklicks.com/blog/making-a-facebook-feed-using-the-graph-api-json-and-jquery/291/ but I am having trouble formatting the date given by facebook. My website is http://moussesalon.com/homePage.htm and my code is as follows:
(function($){
$.fn.fbstatus = function(options) {
set = jQuery.extend({
username: 'Removed for privacy',
token: 'Removed for privacy',
loading_text: null
}, options);
function fbstatus_link(text){
return text.replace(/(href="|<a.*?>)?[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function($0, $1) {
return $1 ? $0 : $0.link($0);
});
}
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "Removed for privacy";
$(this).each(function(i, widget){
var loading = $('<p class="loading">'+set.loading_text+'</p>');
var theObject = $(this);
if (set.loading_text) $(widget).append(loading);
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<ul>";
//loop through and within data array's retrieve the message variable.
$.each(json.data,function(i,fb){
if (fb.message) {
html += "<li>" + fbstatus_link(fb.message) + "<br>" + fb.created_time + "</li>" + "<br>";
}
});
html += "</ul>";
//A little animation once fetched
theObject.animate({opacity:0}, 500, function(){
theObject.html(html);
});
theObject.animate({opacity:1}, 500);
});
});
};
})(jQuery);
Any help would be greatly appreciated.

According to the main Graph API Documentation under 'Dates' you can ask the API to return results in any date format you want - why not just get Facebook to return the dates in your preferred format?
Excerpt from docs:
All date fields are returned as ISO-8601 formatted strings. You can optionally override the date format by specifying a "date_format"
query parameter. The accepted format strings are identical to those
accepted by the php date function. For example,
https://graph.facebook.com/platform/feed?date_format=U returns the
Platform page's feed, with unixtime-formatted dates.

You could use the javascript function
string.substring(from, to);
This will allow you to specify the start character (0 for the start of the string) to the last character you want (length - 5)
fb.created_time.substring(0,(fb.created_time.length-5));

Here is a simple way to do this...
//graph API call
https://graph.facebook.com/YOURNAME?fields=YOURFIELDSHERE&date_format=F j, Y, g:i a&access_token=ACCESSTOKENHERE"
The results will be the date of the post such as; April 13, 2017, 4:40 pm

Related

using the HolidayAPI for bank holidays

the Question:
How can I use the API to return a boolean value if the date is a bank holiday?
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
if i was to use this code:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=25 returns {"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=26 returns {"status":200,"holidays":[]}
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day; if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/
If you simply want to return a true value if the selected date is a holiday, or false if it is not, you could use a function like this:
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0]; inside of the if statement.
The holidays object must be called as a child of the returned data object:
Since the holidays object is an array you'll also need to use an index to access an item. Assuming there is at least one item returned, you would get the date like so:
var myDate = data.holidays[0].date;
However you should always check that there's at least one object in the array before getting the first one:
if(data.holidays.length > 0){...}
Incidentally, if all you want to do is check if there's a holiday on any particular day then this if statement is all you'll need, since an array length of more than zero means there's at least one holiday.
Edit
A full answer to your question, you could put this inside the .done() method:
var isAHoliday = false;
if(data.holidays.length > 0){
// There's at least one holiday today!
isAHoliday = true;
}
You don't have to declare a local variable, you'll probably use one that's declared elsewhere but that's up to you.

Get String value between two strings through javascript

I want to get the string value between ";L0|" and ";GTSet" from the following type of strings.
var test = "GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
var test2 = "GP0|#15a06b93-f7aa-4dda-b0d6-7bf2d2905f27;L0|#015a06b93-f7aa-4dda-b0d6-7bf2d2905f27|Special Event;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
Here is what i have done already.
var str = test2.match(";L0|" + "(.*?)" + ";GTSet");
alert(str[1]);
and this returns a string from the very beginning till the ";GTSet"
Jsfiddle link here
I guess you are getting this value from SharePoint Search results, right? If so, according to Automatically created managed properties in SharePoint Server 2013:
Data format for Managed Metadata.
To query for items tagged with a Managed Metadata field, you have to
use the Unique Identifier for each label. You can find the Unique
Identifier for each term in a term set in the Term Store Management
Tool, on the GENERAL tab. In addition, the data format that is used in
the query has to specify from which level in the term set the query
should apply. This specification is set by adding one of the following
prefixes to the Unique Identifier:
To query for all items that are tagged with a term: GP0|#
To query for all items that are tagged with a child of term: GPP|#
To query for all items that are tagged with a term from a term set: GTSet|#
Based on this information the following example demonstrates how to parse search result value for managed metadata:
function parseTaxonomySearchResultValue(val){
var taxValue = {TermSetGuids: [], TermValues: []};
var parts = val.split(';');
parts.forEach(function(part){
if (part.startsWith("GP0|#")) //term?
{
var termGuid = part.replace("GP0|#", "");
taxValue.TermValues.push({ TermGuid: termGuid});
}
else if (part.startsWith("GTSet|#")) //term set?
{
taxValue.TermSetGuids.push(part.replace("GTSet|#", ""));
}
else if (part.startsWith("L0|#")) //Term with label?
{
var termParts = part.replace("L0|#0", "").split('|');
var termGuid = termParts[0];
var termLabel = termParts[1];
var result = taxValue.TermValues.filter(function(tv){
return tv.TermGuid == termGuid;
});
if (result.length == 0)
taxValue.TermValues.push({TermGuid : termGuid, Label : termLabel});
else
result[0].Label = termLabel;
}
});
return taxValue;
}
//Usage
var taxValue = 'GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc';
var taxValue = parseTaxonomySearchResultValue(taxValue);
document.getElementById('output').innerHTML = "Term info:<br/>" + "Guid= " + taxValue.TermValues[0].TermGuid + "<br/> Label= " + taxValue.TermValues[0].Label;
<div id='output'/>

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

defining date in json file

I wonder to know how to set today's date in json file like we are using in js.
Is there any option to specify Date.today() in json file?
Because, json data has date object which specifies system date whenever we read the json file.
Hope, you will understand what i am trying to say.
Thanks in advance,
-Raja.
Server side can generate JSON dates in ISO format for example "2012-04-30T02:15:12.356Z"
Then client side can parse and load into date object
new Date(Date.parse("2012-04-30T02:15:12.356Z"))
JSON is a structured transport format. It does not have logic in it.
But here are options:
Why not just get the date when you read the file instead?
Have a server generate that JSON that includes the date at which it was generated. However, this is not ideal if you want the current date. By the time you read the file, the date generated by the server is already past.
build a parser that parses a string and make it search for custom markup.
For example, special markup is contained in #{}. Get the command inside, determine the command, and execute replacement.
var jsonString = '{"data1" : "foo","date" : "#{currentdate}"}'
In this case, I'll find #{currentdate}. I should create a function corresponding to this command to replace #{currentdate} into the current date during read (in the format you want)
var parsedString = jsonString.replace(/#\{(\w+)\}/g, function(match, group) {
if (group === 'currentdate') {
return new Date();
}
else if (group === 'anotherCommand') {
return 'anotherValue';
} //and so on
});
and the result is like this:
jsonString = '{"data1" : "foo","date" : "Fri May 04 2012 01:17:07 GMT-0700 (PDT)"}'
I suggest that you consider using the JSON-js (json2.js) parser, because it parses all standard JSON, but also allows you to add custom parse handling logic, called a reviver function, which fits your scenario very well. The basic syntax to invoke the JSON parser with a custom handler looks like this:
var myObject = JSON.parse(myJSONtext, reviverFunction);
Using your example input as a guide, it could be set up to work like this:
var jsonTxt = '[{' +
'"data1": "foo",' +
'"Date": "",' +
'"childs": [{' +
'"data2": "stack",' +
'"Date": ""' +
'}{}{}...]}]'; //and-on-and-on as in your comment
myData = JSON.parse(jsonTxt, function ( key, value ) {
if ( key === 'Date') { return new Date(); }
//any additonal custom logic you may need later...
});
A general introduction to JSON-js is provided at the JSON in JavaScript page, along with some brief intro info about JSON, and the page also includes some usage scenarios.
You can consider leveraging popular library like moment.js http://momentjs.com/
Then you can store date as YYYY-MM-DD in json and let moment handle the parsing:
var dateString = '2012-11-01';
var someday = moment(dateString);
var formattedDate = someday.format('ddd, DD MMM YYYY'); // 'Thu, 01 Nov 2012'
If you want to store the date, I would prefer to store as a String with a format like yyyy/mm/dd hh:mm:ss or something like that, and parse it in a Date object when I want to read it in the language I need.
obj = {
dates : ['2012/04/30 10:14:23', '2012/05/01 05:34:01']
}
I don't understand exactly what you want, with eval methods (it's an ugly practice), you can add a method to puts the actual date in object, and also adds himself at the children and call the method added in the children.
obj = {
data : "foo",
addDate : function() {
this.date = newDate();
if (this.children) {
for (var i = 0; i < this.children.length; i++) {
this.children[i].addDate = this.addDate;
this.children[i].addDate();
}
}
},
children : [{
data : "foo2"
}]
}
PS if you want to store it in a file, then you have to use the eval method (not recommended) storing the methods as a string or evry time you load the file do
jsonLoaded; // this var has the json that you store in a file;
var addDate = function() {
this.date = newDate();
if (this.children) {
for (var i = 0; i < this.children.length; i++) {
this.children[i].addDate = this.addDate;
this.children[i].addDate();
}
}
this.addDate = null; // remove the function we have added
// delete this.addDate; // if is compatible with browser
}
jsonLoaded.addDate = addDate;
jsonLoaded.addDate();
you cannot stringify json objects with functions, because of this, in the second method after add the method addDate, we remove that from the json object (also you can do delete this.addDate, but i don't know if it works in IE)
Wouldn't it be easier just to calculate the current system data whenever you read the file? I may be lacking context here but I don't see the point in storing that in the document.
If you really need to do so you can do as follows
var jsonObject = {"now":"new Date()"};
var date = eval(jsonObject.now);
it will be good to collect all the dates you want to transfer into a
Collection<String> dates = new ArrayList<String>();
Convert this collection to a json object and then at the receving end,convert it back to date. You can use joda date time API for conversions.
I use Gson in java to create json output, but Gson does not allow me to put javascript functions into the json. So this is what I do: Use replacement tags for the places you want to put code(like one of the earlier answers). Then get the text of the json, replace the tags, and then save the text to your json file:
Map<String, String> dynamicDates = new HashMap<>();
dynamicDates.put("d1", "new Date()");
dynamicDates.put("d2", "new Date(2015, 0, 1, 9, 30)");
dynamicDates.put("d3", "new Date(2015, 0, 1, 12, 30)");
JsonObject json = new JsonObject();
JsonObject root = new JsonObject();
JsonObject level_1_A = new JsonObject();
JsonObject level_1_B = new JsonObject();
json.add("root", root);
root.add("level_1_A", level_1_A);
root.add("level_1_B", level_1_B);
level_1_A.addProperty("d1", "${d1}");
level_1_A.addProperty("d2", "${d2}");
level_1_B.addProperty("d3", "${d3}");
StringBuilder sb = new StringBuilder();
new GsonBuilder().setPrettyPrinting().create().toJson(json, sb);
String str = sb.toString();
for (String key : dynamicDates.keySet()) {
str = str.replace("\"${" + key + "}\"", dynamicDates.get(key));
}
String jsonText = str;
String javascriptText = "var myJson = " + str + ";";
System.out.println(jsonText);
System.out.println(javascriptText);
So there is nothing left to be done on the consumption side in using this json. And the first output is:
{
"root": {
"level_1_A": {
"d1": new Date(),
"d2": new Date(2015, 0, 1, 9, 30)
},
"level_1_B": {
"d3": new Date(2015, 0, 1, 12, 30)
}
}
}
My use of json is usually saving it as javascript with an assignment, so this has been working for me.

OAuth nonce value

I am working with the FatSecret REST API
Im using the OAuthSimple javascript library to generate the signed url.
Here's the code I have -
params['oauth_timestamp'] = Math.floor(new Date().getTime()/1000);
params['oauth_nonce'] = '1234';
params['oauth_version'] = '1.0';
var paramStr = '';
for(var key in params){
paramStr += key+"="+params[key]+"&";
}
paramStr = paramStr.substring(0,paramStr.length-1);
var oauth = OAuthSimple();
oauth.setAction('GET');
var o = oauth.sign(
{
path:this.requestURL,
parameters: paramStr,
signatures:{
api_key:this.apiKey,
shared_secret:this.sharedSecret,
access_token: this.accessToken,
access_secret: this.accessSecret
}
});
console.log(o.signed_url);
return o.signed_url;
params is an associative array containing all the non oauth related parameters for this call.
When I use this signed url I get an "invalid/used nonce"
The OAuth Testing Tool uses the same OAuthSimple library and if I put in all the same parameters (including the timestamp) it generates exactly the same url.
The only difference is that the url generated by the testing tool works and gives me the full response from the server. The url generated by my code does't.
I tried various nonce values including sending a MD5 of the timestamp but I get the same error. The reason I'm using 1234 right now is that the testing tool uses 1234 by default and that seems to work.
Any help is appreciated. Thanks in advance.
Updating #Saravanan's answer with something that works on current browsers:
function genNonce() {
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~'
const result = [];
window.crypto.getRandomValues(new Uint8Array(32)).forEach(c =>
result.push(charset[c % charset.length]));
return result.join('');
}
console.info(genNonce());
The nonce value as per twitter documentation:
The value for this request was generated by base64 encoding 32 bytes of random data, and stripping out all non-word characters, but any
approach which produces a relatively random alphanumeric string should
be OK here.
Based on the above notes, I use the following javascript code to generate nonce value each time I send a request:
var nonceLen = 32;
return crypto.randomBytes(Math.ceil(nonceLen * 3 / 4))
.toString('base64') // convert to base64 format
.slice(0, nonceLen) // return required number of characters
.replace(/\+/g, '0') // replace '+' with '0'
.replace(/\//g, '0'); // replace '/' with '0'
Try this if it works!
Try this
This works every time
var nonce = Math.random().toString(36).replace(/[^a-z]/, '').substr(2);

Categories