首页 > 编程知识 正文

各种时间格式的转换公式,时间类型转换格式

时间:2023-05-06 19:48:09 阅读:263339 作者:550

一、毫秒数转换成 需要的时间格式

/*时间格式化*/

    function unixToDatetime(datetime) {

        datetime = parseInt(datetime);

        if (!datetime||datetime< 0) {

            return "";

        }

        var now = new Date(datetime * 1000);

        var year = now.getFullYear(),

            month = now.getMonth() + 1,

            day = now.getDate(),

            hour = now.getHours(),

            minut = now.getMinutes(),

            secon = now.getSeconds();

        if (hour < 10) {

            hour = "0"+hour;

        }

        if (minut < 10) {

            minut = "0"+minut;

        }

        if (secon < 10) {

            secon = "0"+secon;

        }

        if (year != NaN) {

            return year + "-" + month+"-"+day+ " "+hour+ ":"+minut+ ":"+secon;

        } else {

            return ""

        }

    }


二、格式化的时间转成毫秒数

var datetime=newDate(item.ask_time);

//格式从2016-11-22 09:36:59转为Tue Nov 22 2016 09:36:59 GMT+0800 (CST);只有这样下一步才能转成毫秒;

datetime=Date.parse(datetime);//转换成毫秒

var time=newDate().getTime()-datetime;//获取当前时间毫秒减去上面的时间毫秒数,就得到相差的时间,根据需要再转成相应的格式


//下面三行代码是考虑兼容后的写法,在移动端亲测可用,具体参考后一篇文章,我也是刚从坑里爬出来。

var str=item.ask_time;

var datetime=new Date(Date.parse(str.replace(/-/g,"/"))).getTime();  //考虑移动端的兼容

var time=new Date().getTime() - datetime;//获取当前时间毫秒




//时间格式化,返回距离当前的时间

function reTime(time){

var m=Math.floor(time/(1000*60));

var h=Math.floor(time/(1000*60*60));

var d=Math.floor(time/(1000*60*60*24));

var mon=Math.floor(time/(1000*60*60*24*30));

var yea=Math.floor(time/(1000*60*60*24*30*12));

if(m < 60){

returnm+'分钟前';

} else if(0<h&&h<24){

returnh+'小时前';

} else if(0<d&&d<=30){

returnd+'天前'

}else if(0<mon&&mon<12){

returnmon+'个月前'

}else{

returnyea+'年前'

}

}




版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。