I have this string given to me by youtube rss data and I can grab it and store it, but I dont know how to manipulate the string into something that I am trying to use it for.
2012-08-08T16:49:52.000Z
I want to use the string above and create a jquery function that will parse it and spit out how long ago the video was uploaded. ex: 1 day ago, 15 days ago, 20 days ago. I dont expect the parsing to be too much work, but if the logic behind figuring out how many days ago a video was uploaded is very hard, then I will just display the upload date as month day. ex: Aug 8
In short:
- I need to grab the date before the T character in the provided string
- Then display it as 3 days ago format or month day format
I do not know how to do either of these. Hopefully someone can help me. 🙂
UPDATE: So I have grabbed and seperated the date from the rest of the upload information thanks to a comment in this post.
var uploadDate = x.substring(0, x.indexOf('T'));
giving me 2012-08-08
UPDATE 2: I have parsed out the month and day with split()
var date = uploadDate.split('-');
var month = date[1];
var day = date[2];
MY CODE after the ANSWER was given
function differenceDate(dateStr) {
var dateString = dateStr.split('T')[0];
var date = dateString.split('-');
var firstDate = new Date(parseInt(date[0],10), parseInt(date[1],10)-1, parseInt(date[2],10));
var secondDate = new Date();
var diffDate = secondDate.getTime() - firstDate.getTime();
var converted = diffDate/1000/60/60/24;
var uploaded;
if(converted < 1){
uploaded = 'few hours ago';
} else if(converted>1 && converted<2){
uploaded = '1 day ago';
} else if(converted>2){
var daysAgo = Math.floor(converted);
uploaded = daysAgo+ ' days ago';
}
return uploaded;
}
var daysAgo = differenceDate( '2012-08-08T16:49:52.000Z' );
Since you can grab the date string, i assume you can split it from ‘T’ char and send index 0 of result array to your favorite date difference function 🙂 i.e.
After this, all you have to do is check the millis variable and find out if the video was uploaded just minutes ago, some hours ago or maybe years ago.