欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

时间戳转时间格式,时间格式转xx小时前

程序员文章站 2022-04-15 21:29:47
...
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  0) {
        return d_hours + "小时前";
    } else if (d_hours  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) || ('0' + (time.getMonth() + 1)) var date = time.getDate() > 9 && time.getDate() || ('0' + time.getDate()) var hour = time.getHours() > 9 && time.getHours() || ('0' + time.getHours()) var minute = time.getMinutes() > 9 && time.getMinutes() || ('0' + time.getMinutes()) var second = time.getSeconds() > 9 && time.getSeconds() || ('0' + time.getSeconds()) var YmdHis = year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
    return YmdHis;
}
var timestamp = '1466076718000';
timestamp = timestamp.replace(/^\s+|\s+$/, '');
if (/^\d{10}$/.test(timestamp)) {
    timestamp *= 1000;
} else if (/^\d{13}$/.test(timestamp)) {
    timestamp = parseInt(timestamp);
} else {
    alert('时间戳格式不正确!');
    return;
}
var YmdHis = format(timestamp);
alert(YmdHis);