Search

Nov 20, 2015

Get timing compared to the current time (php + javascript)

PHP Code
/**
 * Get timing compared to the current time
 * @param $time
 * @return string
 */
function toTimeNotify($time)
{
    $timeMinus = time() - $time;
    $timeMinus = ($timeMinus < 2) ? 2 : $timeMinus;

    if ($timeMinus <= 24 * 3600) {
        $interval = floor($timeMinus / 3600);
        if ($interval > 1) return $interval . " hours ago";
        $interval = floor($timeMinus / 60);
        if ($interval > 1) return $interval . " minutes ago";
        return floor($timeMinus) . " seconds ago";
    } else {
        return date('d.m.y H:i',$time);
    }
}

Javascript Code

/**
 * Convert string time for notification
 * @param time - the seconds since midnight, 1 Jan 1970
 * @returns {string} - time
 */
var toTimeNotify = function (time) {
    var current = new Date().getTime() / 1000;
    current = parseInt(current);
    var timeMinus = current - time;
    timeMinus = (timeMinus < 1) ? 2 : timeMinus;

    if (timeMinus <= 24 * 3600) {
        var interval = Math.floor(timeMinus / 3600);
        if (interval > 1) return interval + " hours ago";
        interval = Math.floor(timeMinus / 60);
        if (interval > 1) return interval + " minutes ago";
        return Math.floor(timeMinus) + " seconds ago";
    } else {
        var createDate = new Date(time * 1000);
        var dd = createDate.getDate(),
            mm = createDate.getMonth(),
            y = createDate.getFullYear(),
            hh = createDate.getHours(),
            ii = createDate.getMinutes();
        return (dd + '.' + mm + '.' + y + ' ' + hh + ':' + ii);
    }
};

No comments:

Post a Comment