简体   繁体   中英

javascript Date Object how long ago

I'm trying to show how long ago a video was uploaded, i cant seem to get the hours and minutes Date Object Methods to work in this script. I'm working of a script called YouMax 2.0 and i have been editing the function getDateDiff, i have come up with this edit of the function . Thank you for any help on this.

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 d1T = d1.getMinutes();
var d2T = parseInt(splitTime[1], 10);
var diffInMinutes = (d1T + 59 * d1H + 23) - (d2T + 59 * d2H + 23);
if (diffInMinutes <= 1) return "1 Minute";
else if (diffInMinutes <= 59) return diffInMinutes + " Minutes";
var diffInHours = (d1H + 23 * d1M) - (d2H + 23 * d1M);
if (diffInHours <= 1) return "1 Hour";
else if (diffInHours < 23) return diffInHours + " Hours";
var diffInDays = (d1D + 30 * d1M + 12 * d1Y) - (d2D + 30 * d2M + 12 * 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";
}

my new function only returns minutes and other and wont update to change of day

I assume you are fetching the timestamp from a mysql database. This was also answered here . The top answer is in php but it is not really different from Javascript. I do suggest using php for this however.

you can see that your splitting was not correct... this is working fine..

var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var splitTime1 = ((splitTime[2].toString().split('Z'))[0]).split('.');

splitDate[0] = Year;
splitDate[1] = Month;
splitDate[2] = Day;

splitTime[0] = Hours;
splitTime[1] = Minutes;
splitTime1[0] = Seconds;
splitTime1[1] = MilliSeconds;

you can now perform what ever you want to..

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM