js时间戳及标准时间的互转,标准时间补0,(new Date获取的是当前服务器时间,非互联网时间)

1、获取当前服务器的标准时间及时间戳


let date = new Date(); // 中国标准时间
let time = new Date().getTime(); // 时间戳
console.log(date) // Mon Oct 31 2022 09:10:22 GMT+0800 (中国标准时间)
console.log(time) // 1667178622175

2、标准时间转换成年月日时分秒(补0),如:2022-10-31 09:10:22


// 标准时间转换成年月日时分秒(补0)
function getTime(date) {
  let Y = date.getFullYear(),
	M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),
	D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()),
	h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()),
	m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()),
	s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
  return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
}
console.log(getTime(date)) // 2022-10-31 09:10:22

3、时间戳转成标准时间 ,如:Mon Oct 31 2022 09:24:58 GMT+0800 (中国标准时间)


// 时间戳转成标准时间
function getStampTime(time) {
  return new Date(time)
}
console.log(getStampTime(time))	// Mon Oct 31 2022 09:24:58 GMT+0800 (中国标准时间)


Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐