how can I use my function JSONtoDate inside $.getJSON? This doesn´t work... val.timePosted return a string like 1448038589396, this work fine without the function but when I trying use the function to convert the str to date everything disappear
$(document).ready(function() {
function JSONtoDate(num){
var month = num.getMonth() + 1;
var day = num.getDate();
var year = num.getFullYear();
var date = day + "/" + month + "/" + year;
return(date);
}
$.getJSON("http://www.freecodecamp.com/news/hot", function(json) {
var html = "";
var count = 0;
json.map(function(val) {
if(count == 0){
html += "<div class = 'row' >";
}
html += "<div class = 'stories col-md-3'>";
html += "<a href = " + val.link + " > <img src = " + val.image + " width = ' 200px'>";
html += "<p>" + val.headline + "</p> </a>";
html += "<p>" + val.rank + "</p>";
html += "<p>" + JSONtoDate(val.timePosted) + "</p>";
html += "</div>";
count += 1;
if(count == 4){
html += "</div>";
count = 0 ;
}
});
$(".section").html(html);
});
});
You have a JS error here:
1448038589396 is not a Date Object and it throws :
Uncaught TypeError: num.getMonth is not a function
try the following in jsFiddle
in JSONtoDate try the following
function JSONtoDate(num){
var num = new Date(num);
var month = num.getMonth() + 1;
var day = num.getDate();
var year = num.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}
I converted a string to UNIX timestamp based new Date() Object
Your function JSONtoDate
expects a Date
object as parameter, but you provide a String
- "1448038589396"
. You can either pass a date, constructed from the Number
value val.timePosted
html += "<p>" + JSONtoDate(new Date(parseInt(val.timePosted))) + "</p>";
^^^^^^^^^^^^^^^^^^ ^^
or let your function accept a string
parameter:
function JSONtoDate (dateString) {
var date = new Date(parseInt(dateString));
var month = date.getMonth() + 1;
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.