fxxqq / 6fedcom.github.io

frank的前端养成记(hexo博客)
https://6fed.com
22 stars 5 forks source link

时间戳转化成年月日时分秒格式 #11

Open fxxqq opened 6 years ago

fxxqq commented 6 years ago
function add0(m){return m<10?'0'+m:m }
//时间戳转化成时间格式
function timeFormat(timestamp){
  //timestamp是整数,否则要parseInt转换,不会出现少个0的情况
    var time = new Date(timestamp);
    var year = time.getFullYear();
    var month = time.getMonth()+1;
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    return year+'-'+add0(month)+'-'+add0(date)+' '+add0(hours)+':'+add0(minutes)+':'+add0(seconds);
}

es6写法

function formatNumber(n) {
    const str = n.toString()
    return str[1] ? str : `0${str}`
}

export function formatTime(date) { 
    date=new Date(date)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    const t1 = [year, month, day].map(formatNumber).join('/')
    const t2 = [hour, minute, second].map(formatNumber).join(':')

    return `${t1} ${t2}`
}