js时间戳转日期方法

js 时间戳转日期方法

/**
 * [formatDateTime 时间戳转年月日 时分秒]
 * @param  {[type]}  int [时间戳]
 * @param  {[type]}  str [时间格式,格式如下]
 * 时间格式,[y-m-d h:i:s , y-m-d , h:i:s , ymdhis , y-m , m-d , y 年 m 月 d 日 , y 年 m 月 , m 月 d 日 , y 年 m 月 d 日 h 时 i 分 s 秒 , h 时 i 分 s 秒]
 * @param  {Boolean} bol [默认为 true ,表示 10 以下前面补零]
 * @return {[type]}      [返回对应格式的日期时间格式]
 */
function formatDateTime(int, str, bol = true) {
    let date = new Date(int);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    if (bol) {
        month = month < 10 ? '0' + month : month
        day = day < 10 ? '0' + day : day
        hours = hours < 10 ? '0' + hours : hours
        minutes = minutes < 10 ? '0' + minutes : minutes
        seconds = seconds < 10 ? '0' + seconds : seconds
    }
    let strtoLowerCase = str.toLowerCase(); //把传入的转换成小写
    console.log(strtoLowerCase)
    switch (strtoLowerCase) {
        case 'y-m-d h:i:s':
            return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
            break;
        case 'ymdhis':
            return year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds;
            break;
        case 'y-m-d':
            return year + '-' + month + '-' + day;
            break;
        case 'y-m':
            return year + '-' + month;
            break;
        case 'm-d':
            return month + '-' + day;
            break;
        case 'ymd':
            return year + '' + month + '' + day;
            break;
        case 'h:i:s':
            return hours + ':' + minutes + ':' + seconds;
            break;
        case 'his':
            return hours + '' + minutes + '' + seconds;
            break;
        case 'y 年 m 月 d 日 h 时 i 分 s 秒':
            return year + '年' + month + '月' + day + '日' + ' ' + hours + '时' + minutes + '分' + seconds + '秒';
            break;
        case 'y 年 m 月 d 日':
            return year + '年' + month + '月' + day + '日';
            break;
        case 'h 时 i 分 s 秒':
            return hours + '时' + minutes + '分' + seconds + '秒';
            break;
        case 'y 年 m 月':
            return year + '年' + month + '月';
            break;
        case 'm 月 d 日':
            return month + '月' + day + '日';
            break;
    }
}
document.write("时间戳: "+new Date());
document.write("<br>");
document.write("转换结果: "+formatDateTime(new Date(), 'y 年 m 月 d 日', bol = true))

「点点赞赏,手留余香」

1

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » js时间戳转日期方法

发表回复