JS Create A Date Object from value passed via AJAX Call - javascript

I have a Python script that returns me a calculated date time in XML format like below:
<prev><date>2012,07,16</date><time>22:00:00</time></prev>
Though I can change the format but my issue is that when I try creating a JS date object using the value returned - I get 'Invalid date':
$.ajax({
async: false,
type: "POST",
url: "/cgi-bin/prev_hour.py",
success: function(xml)
{
pdate = $(xml).find('date').text();
ptime = $(xml).find('time').text();
//alert prints correct date time ex 2012-07-16 22:00:00
},
error:function(xhr,err,html)
{
alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
}
var max_date = new Date("'" + pdate + ptime + "'");
alert(max_date);
I tried a couple of possibilities like Python script returning in various format:
<prev><date>2012/07/16 </date><time>22:00:00</time></prev>
<prev><date>2012,07,16 </date><time>22,00,00</time></prev>
But still I get invalid date when trying to create a JS date object?
Please let me know the correct way to implement it.

You don't need the extra set of quotes in your date string, and you will need a space between the date and time components, try:
new Date(pdate + " " + ptime);

Try using amazing lib for dates called Moment.js
moment("2012/07/16 22:00:00")
from there you can achieve everything with dates.

This:
var max_date = new Date("'" + pdate + ptime + "'");
Should be:
var max_date = new Date(pdate + ' ' + ptime);
Next time you run into such issues put an alert on the value you are sending to the function and see what it looks like.

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.

How to get specific value from iTunes API using Javascript

This is my API call:
https://itunes.apple.com/search?term=cut+the+cord&limit=1
I only want to get the value of the '"releaseDate":"2015-06-29' part.
Is there any way that I could only get that part in a textbox. I have this textbox in another page. Any ideas or suggestions?
Due to the cross-domaine policy, you must use JSONP to get json data and then format response value:
$.ajax({
url: "http://itunes.apple.com/search?term=cut+the+cord&limit=1",
dataType: "jsonp",
success: function( response ) {
console.log( response );
var d = new Date(response.results[0].releaseDate);
var y = d.getFullYear();
var m = pad( d.getMonth()+1, 2);
var d = pad( d.getDate(), 2);
$("#release").attr('value', y + "-" + m + "-" + d)
}
});
http://jsfiddle.net/yts728L5/2/
I guess you're parsing your result as JSON:
var result = JSON.parse(apiCallResult)
Then, assuming you only have one result as in the example request above, you should be able to get that value by simply accessing the object:
var results = result.results;
var releaseDate = results[0].releaseDate;
This will work if you have multiple results also, but it will only take the first result's releaseDate.
To add the text to a text box, you can use jQuery to get the text box and then set its value:
var textBox = $("#myTextBoxId");
textBox.val(releaseDate);

Convert Date in to custom format in javascript

I have a Date format like this
2014-11-18T20:50:01.462Z
I need to convert to the custom format like "20:50 2014-18-11" using Javascript date function
I need result like
20:50 2014-18-11
How to get this , Thanks in Advance :)
Assuming you're able to include new libraries on your project, I'd highly recommend moment.js (MIT license) instead of writing this yourself. It solves problems like zero padding etc. for you.
Example
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script>
// Use an existing date object
var date = new Date("2014-11-18T20:50:01.462Z");
console.log(moment(date).format('HH:mm YYYY-DD-MM'));
// or use string directly
console.log(moment.utc("2014-11-18T20:50:01.462Z").format('HH:mm YYYY-DD-MM'));
</script>
Note by default moment will use your current timezone for output, this can be overridden using the zone() function
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone(0).format('HH:mm YYYY-DD-MM'));
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone('UTC+05:30').format('HH:mm YYYY-DD-MM'));
Output
20:50 2014-18-11
Try moment js its very nice plugin to play around dates and times
so all you need to do is import moment js and put this line in your js code
using moment.js will also help you in future for your code
moment.utc("2014-11-18T20:50:01.462Z").format("HH:mm YYYY-DD-MM")
Use this Demo JsFiddler
var d = new Date,
dformat = [ d.getHours().padLeft(), d.getMinutes().padLeft()].join(':')
+ ' ' +
[d.getFullYear(), d.getDate().padLeft(), (d.getMonth()+1).padLeft()].join('-')
;
Date.prototype._padding = function(v, w) {
var f = "0000" + v;
return ("0000" + v).substr(f.length-w, f.length)
}
Date.prototype.MyDateString = function() {
return this._padding(this.getUTCHours(), 2) + ":" + this._padding(this.getUTCMinutes(), 2) + " " + this.getUTCFullYear() + "-" + this._padding(this.getUTCDate(), 2) + "-" + this._padding((this.getUTCMonth() + 1), 2);
}
console.log(new Date('2014-11-18T20:50:01.462Z').MyDateString())
console.log(new Date('2014-11-08T02:05:01.462Z').MyDateString())
getUTCMonth return 10, as the month is 0 based.

Format Date in Javascript/JQuery as Single Digit Day

Currently, I am pulling in a json feed from our calendar. It brings back the date in the yyyy/mm/dd format... I know I can overwrite this format by using javascript but how would I do this? I need the output to only be the "dd" not the month nor the year.
I would also like single digit days to show up as i.e. "1","2","3","4" and of course dbl digits to show up as usual "10", "11", "12", etc. Any ideas on how I could achieve this reformatting of the date via javascript/jquery?
You can use a Date object
var theDate = new Date(dateString);
var theDay = parseInt(theDate.getDate(), 10);
Alternatively, if you don't want to use the object and can expect the same string back each time:
var theDay = parseInt(dateString.split('/')[2], 10);
This code should do it . . .
var jsonDate = <...reference to the JSON date value...>;
var dayValue = jsonDate.split("/")[2].replace(/0(.)/, "$1");
You've already got a string value, so might as well just manipulate it as a string.
jsonDate.split("/")[2] splits up the full date and then takes the third item from the resulting array (i.e., the day value)
.replace(/^0(.)$/, "$1") will trim off the "0", if it finds it in the first position of the "day" string
Then you just use dayValue wherever you need to use it. :)
UPDATE:
Based on the comments below, try using this as your code:
var listingEl = $('<div class="eventListings" title="' + item.event.title + '" />');
var dateEl = $('<div class="mdate">' + dayValue + '</div>');
var linkEl = $('<a href="' + item.event.localist_url + '" />');
var titleEl = $('<div class="mcTitle">' + item.event.title + '</div>');
linkEl.append(titleEl);
listingEl.append(dateEl);
listingEl.append(linkEl);
$('#localistTitle').append(listingEl);
UPDATE 2:
There was something not working in your code (I think the main issues was how you were using .appendTo()). I split it out into a multi-step process and used .append() instead. It worked correctly when I tested it locally.

How to Format fb.created_time

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

Categories