js 时间戳 日期转化

js 时间戳 日期转化

function formatDate(time,format='YY-MM-DD hh:mm:ss'){
    var date = new Date(time);

    var year = date.getFullYear(),
        month = date.getMonth()+1,//月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
    var preArr = Array.apply(null,Array(10)).map(function(elem, index) {
        return '0'+index;
    });////开个长度为10的数组 格式为 00 01 02 03

    var newTime = format.replace(/YY/g,year)
                        .replace(/MM/g,preArr[month]||month)
                        .replace(/DD/g,preArr[day]||day)
                        .replace(/hh/g,preArr[hour]||hour)
                        .replace(/mm/g,preArr[min]||min)
                        .replace(/ss/g,preArr[sec]||sec);

    return newTime;         
}
formatDate(new Date().getTime());//2017-05-12 10:05:44
console.log(formatDate(new Date().getTime(),'YY年MM月DD日'));//2017年05月12日
formatDate(new Date().getTime(),'今天是YY/MM/DD hh:mm:ss');//今天是2017/05/12 10:07:45

时间转时间戳:javascript获得时间戳的方法有四种,都是通过实例化时间对象 new Date() 来进一步获取当前的时间戳

1.var timestamp1 = Date.parse(new Date()); // 结果:1477808630000 不推荐这种办法,毫秒级别的数值被转化为000

console.log(timestamp1);

2.var timestamp2 = (new Date()).valueOf(); // 结果:1477808630404 通过valueOf()函数返回指定对象的原始值获得准确的时间戳值

console.log(timestamp2);

3.var timestamp3 = new Date().getTime(); // 结果:1477808630404 ,通过原型方法直接获得当前时间的毫秒值,准确

console.log(timestamp3);

4.var timetamp4 = Number(new Date()) ; //结果:1477808630404 ,将时间转化为一个number类型的数值,即时间戳

猜你喜欢

转载自blog.csdn.net/qq_37167049/article/details/83990857