各种时间转换

发布时间 2023-03-27 20:12:22作者: WALL*E

一、时间格式

 //转化  
getTime(){
//1、2023-03-25T06:14:51.000+00:00转化为 2023-03-25 06:14:52 格式
      const string=2023-03-25T06:14:51.000+00:00
      let timess = new Date(string);
//2、获取当前时间并转换为2023-03-25 06:14:52
      let timess = new Date();
      const formTime = {
        y: timess.getFullYear(),
        m: timess.getMonth() + 1,
        d: timess.getDate(),
        h: timess.getHours(),
        s: timess.getMinutes(),
        ss: timess.getSeconds()
      };
     return formTime.y+'-' + ("0" + (formTime.m)).slice(-2)+'-'+("0" + (formTime.d)).slice(-2)+' '+("0" + (formTime.h)).slice(-2)+':'+("0" + (formTime.s)).slice(-2)+':'+("0" + (formTime.ss)).slice(-2)
    },

二、 时间差

dateDiff(date1,date2){
     var d1 =new Date(date1);
     var d2 = date2 ? new Date(date2) :new Date();
     var time =Math.abs(d1.getTime()-d2.getTime());
     var day = parseInt(time/1000/60/6024);
     var  h=parseInt((time -day*1000*60*60*24)/1000/60/60);
     var m =parseInt((time-day*24*60*60*1000-h*60*60*1000)/60/1000);
     var s=parseInt((time-day*24*60*60*1000-h*60*60*1000-m*60*1000)/1000);
     return{
       day,
       h,
       m,
       s,
    }
 }
var res1 = dateDiff("2008.8.8 20:8:8" ,"1997.7.1")
console.log(res1)
var res2= dateDiff("1997.7.1");
console.log(res2)

三、// 当前时间

export function getTime (type:string){
  let timess = new Date();
  const formTime = {
    y: timess.getFullYear(),
    m: timess.getMonth() + 1,
    d: timess.getDate(),
    h: timess.getHours(),
    s: timess.getMinutes(),
    ss: timess.getSeconds()
  };

	if(type=='yyyy-mm-dd-top'){//当月一号
		return formTime.y+'-' + ("0" + (formTime.m)).slice(-2)+'-'+("01") ;
	}else	if(type=='yyyy-mm-dd-bottom'){//当前月最后一天
		let day = 31
		switch (formTime.m){
			case 1||3||5||7||8||10||12:
				return day=31;
			case 2:
				return day=28;
			case 4||6||9||11:
				return day=30;
			default: day=31;
		}
		return formTime.y+'-' + ("0" + (formTime.m)).slice(-2)+'-'+day;
	}else	if(type=='yyyy-mm-dd'){//当前时间 yyyy-mm-dd
		return formTime.y+'-' + ("0" + (formTime.m)).slice(-2)+'-'+("0" + (formTime.d)).slice(-2);
	}else if(type=="yyyy-mm-dd HH:MM:ss"){//当前时间 yyyy-mm-dd HH:MM:ss
		return formTime.y+'-' + ("0" + (formTime.m)).slice(-2)+'-'+("0" + (formTime.d)).slice(-2)+' '+("0" + (formTime.h)).slice(-2)+':'+("0" + (formTime.s)).slice(-2)+':'+("0" + (formTime.ss)).slice(-2)
	} else{
		return formTime.y+ ("0" + (formTime.m)).slice(-2)+("0" + (formTime.d)).slice(-2)+("0" + (formTime.h)).slice(-2)+("0" + (formTime.s)).slice(-2)+("0" + (formTime.ss)).slice(-2)
	}
}