首頁  >  文章  >  php教程  >  時間戳轉時間格式,時間格式轉xx小時前

時間戳轉時間格式,時間格式轉xx小時前

大家讲道理
大家讲道理原創
2016-11-08 11:31:361214瀏覽


mysql時間戳傳到前台,百度的那些都轉換代碼都不可用。此程式碼片段是從一個線上轉換網站扣的。

/**
 * 将时间转换为 xx小时前
 * @param {Object} pTime
 */
function jsDateDiff(pTime) {
    var d_minutes, d_hours, d_days, d;
    var timeNow = parseInt(new Date().getTime() / 1000);
    pTime_new = new Date(pTime).getTime() / 1000;
    d = timeNow - pTime_new;
    d_days = parseInt(d / 86400);
    d_hours = parseInt(d / 3600);
    d_minutes = parseInt(d / 60);
    if (d_days > 0 && d_days < 4) {
        return d_days + "天前";
    } else if (d_days <= 0 && d_hours > 0) {
        return d_hours + "小时前";
    } else if (d_hours <= 0 && d_minutes > 0) {
        return d_minutes + "分钟前";
    } else {
        return pTime;
    }
}
function format(timestamp) {
    var time = new Date(timestamp);
    var year = time.getFullYear();
    var month = (time.getMonth() + 1) > 9 && (time.getMonth() + 1) || (&#39;0&#39; + (time.getMonth() + 1)) var date = time.getDate() > 9 && time.getDate() || (&#39;0&#39; + time.getDate()) var hour = time.getHours() > 9 && time.getHours() || (&#39;0&#39; + time.getHours()) var minute = time.getMinutes() > 9 && time.getMinutes() || (&#39;0&#39; + time.getMinutes()) var second = time.getSeconds() > 9 && time.getSeconds() || (&#39;0&#39; + time.getSeconds()) var YmdHis = year + &#39;-&#39; + month + &#39;-&#39; + date + &#39; &#39; + hour + &#39;:&#39; + minute + &#39;:&#39; + second;
    return YmdHis;
}
var timestamp = &#39;1466076718000&#39;;
timestamp = timestamp.replace(/^\s+|\s+$/, &#39;&#39;);
if (/^\d{10}$/.test(timestamp)) {
    timestamp *= 1000;
} else if (/^\d{13}$/.test(timestamp)) {
    timestamp = parseInt(timestamp);
} else {
    alert(&#39;时间戳格式不正确!&#39;);
    return;
}
var YmdHis = format(timestamp);
alert(YmdHis);


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn