let time = new Date()
console.log(time)      //打印结果为:Wed Aug 31 2022 10:47:48 GMT+0800 (中国标准时间)

以2023年1月15号为例,列出三种时间格式形式:
中国标准时间-格式: Sun Jan 15 2023 09:51:20 GMT+0800 (中国标准时间)
时间戳-格式: 1673747480123
年-月-日-格式: 2023-01-15

1、中国标准时间转年月日

function get(){
	var date = new Date();
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	if (month < 10) {
	    month = "0" + month;
	}
	if (day < 10) {
	    day = "0" + day;
	}
	var currentdate = year + "-" + month + "-" + day;
	return currentdate 
}

打印结果为 2023-01-15

2、年月日转中国标准时间

let myDate4 = '2023-01-15';
let myDate5 = '2023-01-15 20:00:00';

function formatterDate (date) {
	let result = new Date(date);
	return result;
}

console.log(formatterDate(myDate4));//--->Sun Jan 15 2023 08:00:00 GMT+0800 (中国标准时间)
console.log(formatterDate(myDate5));//--->Sun Jan 15 2023 20:00:00 GMT+0800 (中国标准时间)

3、中国标准时间转时间戳 new Date().getTime()

new Date()           // Sun Jan 15 2023 09:51:20 GMT+0800 (中国标准时间)
new Date().getTime() // 1673747480123

4、时间戳转换成中国标准时间 new Date(start)

获取当前中国标准时间,取上个月这一天的时间。那么就需要先转成时间戳,再减去一个月的时间,再转成中国标准时间就可以了

let start = new Date().getTime() - 3600 * 1000 * 24 * 30;    //console.log(start) //1673747480123

function getSimpleDate(date) {
  let dd = new Date(date) // 时间戳转化成中国标准时间格式
  return dd 
}
getSimpleDate(start )  
//console.log(start)//Sun Jan 15 2023 09:51:20 GMT+0800 (中国标准时间)

5、时间戳转年月日/年月日时分秒

方法一:

formatDate: function (time) {
	let date = new Date(time);//13位时间戳
	//let date = new Date(parseInt(time) * 1000); //10位时间戳
	let y = date.getFullYear();
	let MM = date.getMonth() + 1;
	MM = MM < 10 ? ('0' + MM) : MM;
	let d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	let h = date.getHours();
	h = h < 10 ? ('0' + h) : h;
	let m = date.getMinutes();
	m = m < 10 ? ('0' + m) : m;
	let s = date.getSeconds();
	s = s < 10 ? ('0' + s) : s;
	return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
	// return y + '-' + MM + '-' + d;
},

方法二:

var d=new Date();
var year=d.getFullYear();
var month=formater(d.getMonth()+1);
var date=formater(d.getDate());
var gettime=[year,month,date].join('-');
console.log('时间戳转换为年月日:',gettime);

function formater(temp){
  if(temp<10){
    return "0"+temp;
  }else{
    return temp;
  }
}

6、年月日转换成时间戳

function getStampDate(date) {
  let stamp = new Date(currentDate).getTime() // 年月日转化成时间戳
  //let preDate = new Date(currentDate).getTime() - (24 * 60 * 60 * 1000) // 前一天时间戳
  //let afterDate = new Date(currentDate).getTime() + (24 * 60 * 60 * 1000) // 后一天时间戳
  return stamp
}

用时间戳来计算前一天后和后一天不会出(29号、30号、31号)的误判
Logo

前往低代码交流专区

更多推荐