关于js时间的加减

今天项目中突然遇到一个需求,之前是把db返回来的时间转成yyyy-mm-dd格式就可以。

现在要要用时间和当前的时间做对比,根据相差的不同差距,来绝对显示什么。

这就需要把天数,  月,  年 都需要加入对比判断。

以前不知道怎么取分别取出来对比, 只有把时间都转成了时间搓,

var data=new Data();

var now=data.getTime();

然后再去对比两个时间搓的差值。

但是这种做法做天数差距可以,设计到月时候,因为每个月天数不一样,就麻烦了。

最后找了js 的  setDate(), getDate()方法,分别可以设置, 取出你的时间的是几号,哪一天。

   var dataer=function(dates){
            var d=new Date();
            var e=new Date(dates);
            console.log(d);
            console.log(e);
            console.log(d.getDate(), d.getMonth(),d.getFullYear());//分别取出当前时间的年,月 日。 其中月份需要加1.因为老外的系统中,取月从0 开始的。  -   -
            console.log(e.getDate(), e.getMonth(),e.getFullYear());分别取出传入时间的年,月 日。
            if(e.getFullYear()==d.getFullYear()){
                if(d.getMonth()==e.getMonth()){

                }else if(d.getMonth()-e.getMonth()==1&&e.getDate()>d.getDate()){

                    //console.log(d.getMonth()-e.getMonth()+"月前")
                }else if(d.getMonth()-e.getMonth()==1&&e.getDate()<d.getDate()){
                    //console.log("1个月前")
            return "1个月前";
                    }else if(d.getMonth()-e.getMonth()>1&&d.getMonth()-e.getMonth()<3){
                        console.log("2个月前")
                    }else if(d.getMonth()-e.getMonth()>=3){

                    }
                }else{
                    console.log(dates);
                }

        };
原文地址:https://www.cnblogs.com/joesbell/p/6030247.html