js将时间戳转化为时间,(不省略0)

在写后台管理系统的过程中,遇到将时间戳转化成时间模式的内容

第一反应,去网上搜一波,但是拿来主义并不是很好的,也遇到一些问题

先贴出在网上搜到的js代码

function formatDate(nows) { 
    var now=new Date(nows); 
    var year=now.getFullYear(); 
    var month=now.getMonth()+1; 
    var date=now.getDate(); 
    var hour=now.getHours(); 
    var minute=now.getMinutes(); 
    var second=now.getSeconds(); 
    return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 
}

  

以上的方式是可行的,但是在这个过程中出现了一个问题:如果出现这样的数据:2018-9-27 18:01:00,那么呈现出来的方式是:2018-9-27 18:1:0

有问题解决它:相信大家都能想到的方式就是补0法,采用补0 的方法将数据填充完整

解决方案一:代码如下

function formatDate(nows) {
        if (nows == null || nows == "") {
            return "";
        }
        var now = new Date(nows);
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        if (hour.toString().length < 2) {
            hour = "0" + hour;
        }
        var minute = now.getMinutes();
        if (minute.toString().length < 2) {
            minute = "0" + minute;
        }
        var second = now.getSeconds();
        if (second.toString().length < 2) {
            second = "0" + second;
        }
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }

  

方案一的解决方式是判断位数,如果位数小于两位,拼接一个字符串0

在这个过程中唯一感觉有点别扭的东西是将hour,minute,second进行转化,变成字符串取长度,由于取到的数字是没有长度的,只能通过这种方式进行

解决方案二:代码如下

function formatDate(nows) {
        if (nows == null || nows == "") {
            return "";
        }
        var now = new Date(nows);
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        date = now.getDate();
        var hour = now.getHours();
        if (hour <= 9) {
            hour = "0" + hour+"";
        }
        var minute = now.getMinutes();
        if (minute <= 9) {
            minute = "0" + minute+"";
        }
        var second = now.getSeconds();
        if (second <= 9) {
            second = "0" + second+"";
        }
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }

  

在方案二的执行过程中也是对hour,minute,second进行判断,由于它是数字本身,所以在不进行类型转换的前提下进行数字大小的判断也是可行的。

猜你喜欢

转载自www.cnblogs.com/cswxl/p/9714919.html