Akash Magoon
Akash Magoon

Reputation: 899

display minutes in Javascript

I am using a code library called YOUMAX that displays youtube videos from my channel on my website.

I am having trouble making the videos show up show the correct time uploaded. Right now, I have it to say that it was upload "3 hour ago" or "2 days ago" or "5 months ago"..

But I cannot figure out the code for minutes.

function getDateDiff(timestamp) {
    if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
    var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
    var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
    var d1 = new Date();
    var d1Y = d1.getFullYear();
    var d2Y = parseInt(splitDate[0], 10);
    var d1M = d1.getMonth() + 1;
    var d2M = parseInt(splitDate[1], 10);
    var d1D = d1.getDate();
    var d2D = parseInt(splitDate[2], 10);
    var d1H = d1.getHours();
    var d2H = parseInt(splitTime[0], 10);
    var diffInHours = (d1H + 24 * d1D + 720 * d1M + 12 * d1Y) - (d2H + 24 * d2D + 720 * d2M + 12 * d2Y);
    if (diffInHours <= 1) return "1 Hour";
    else if (diffInHours < 23) return diffInHours + " Hours";
    var diffInDays = (d1D + 30 * d1M + 360 * d1Y) - (d2D + 30 * d2M + 360 * d2Y);
    if (diffInDays < 7) return diffInDays + " days";
    else if (diffInDays > 7 && diffInDays < 14) return "1 week";
    else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + "     weeks";
    var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
    if (diffInMonths <= 1) return "1 month";
    else if (diffInMonths < 12) return diffInMonths + " months";
    var diffInYears = Math.floor(diffInMonths / 12);
    if (diffInYears <= 1) return "1 year";
    else if (diffInYears < 12) return diffInYears + " years";
}

I tried making one for minutes:

var d1T = d1.getMinutes();
var d2T = parseInt(splitTime[1], 10);
var diffInMinutes = (d1T + 60 *d1H + 24 * d1D + 360 * d1M + 12 * d1Y) - (d2T + 60 *d2H + 24 * d2D + 360 * d2M + 12 * d2Y);

if (diffInHours <= 1) return diffInMinutes + " minutes";

However, when I add in the second group of code, the minutes are not displayed correctly. For example, a video that was uploaded 7 minutes ago will display as "947 minutes ago".

Upvotes: 3

Views: 184

Answers (2)

Gildor
Gildor

Reputation: 2574

Try Moment.js which saves all the work.

Upvotes: 1

dev
dev

Reputation: 715

for condition write :

if (diffInMinutes <= 60) return diffInMinutes + " minutes";

instead of

if (diffInHours <= 1) return diffInMinutes + " minutes";

If it also doesn't work use

var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);

Hope it will work.

Upvotes: 0

Related Questions