I've been trying to format my timestamps into the facebook/twitter style where it shows 1 second, 1 day, 1 month, 1 year and so on. However for some reason it's not returning the right values back and i'm not sure why?
Below I've made a copy of the code I'm using and made two examples of the subtracting dates.
It would be good if somebody could help me out and point out the problem and where i'm going wrong in displaying the correct value.
// Returned Result
$("#TimeFormatted").append("Not divided by 1000: " + FormatTimeAgo(SubtractDates("1432215738000")));
$("#TimeFormatted2").append("Divided by 1000: " + FormatTimeAgo(SubtractDates2("1432215738000")));
function FormatTimeAgo(milliseconds)
{
function numberEnding (number) {
return (number > 1) ? 's' : '';
}
var temp = Math.floor(milliseconds / 1000);
var years = Math.floor(temp / 31536000);
// Years ago
if (years) {
return years + ' year' + numberEnding(years);
}
// Days ago
var days = Math.floor((temp %= 31536000) / 86400);
if (days) {
return days + ' day' + numberEnding(days);
}
// Hours ago
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) {
return hours + ' hour' + numberEnding(hours);
}
// Minutes ago
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) {
return minutes + ' minute' + numberEnding(minutes);
}
// Seconds ago
var seconds = temp % 60;
if (seconds) {
return seconds + ' second' + numberEnding(seconds);
}
return 'less than a second'; //'just now' //or other string you like;
}
function SubtractDates(databaseTime)
{
// Current time
var date = new Date().getTime();
// Database value
var mysqlDate = new Date(databaseTime);
var getMYSQLDate = mysqlDate.getTime();
// Subtract dates
var subtractDates = date - getMYSQLDate;
return subtractDates;
}
function SubtractDates2(databaseTime)
{
// Current time
var date = new Date().getTime();
// Database value
var mysqlDate2 = new Date(databaseTime / 1000);
var getMYSQLDate2 = mysqlDate2.getTime();
// Subtract dates
var subtractDates2 = date - getMYSQLDate2;
return subtractDates2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="TimeFormatted"></div>
<div id="TimeFormatted2"></div>
Thank-you in advance!