项目开发中常用:获取当前时间,时间戳转换标准时间格式

项目开发中经常会遇到时间处理的方法:获取当前时间,时间戳转换标准时间格式

1.代码量最少的timeFilter方法来实现获取当前时间+转换时间戳

调试结果:

方法使用

1. 直接调用方法 timeFilter()不传参,则直接返回当前时间2020-06-05 16:36:30

2. 调用方法并传入时间戳 timeFilter(1591346207203),则直接返回标准时间格式2020-06-05 16:36:4

code
function timeFilter (time = +new Date()) {
    const date = new Date(time + 8 * 3600 * 1000);
    return date.toJSON().substr(0, 19).replace('T', ' ');
}
console.log( timeFilter(1591346207203))
console.log( timeFilter())

2.类型之间的转换

2.1 时间戳转换为 yyyy-mm-dd或yyyy-MM-dd HH-mm-ss 

code
 function timestampToTime(timestamp) {
var date = new Date(timestamp );//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear() + '-';
var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1) + '-';
var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate())+ ' ';
var h = (date.getHours() < 10 ? '0'+date.getHours():date.getHours())+ ':';
var m = (date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes()) + ':';
var s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
// return Y+M+D+h+m+s;
if (new Date(timestamp).toDateString() === new Date().toDateString()) {
console.log("当天");
} else if (new Date(timestamp) < new Date()){
		console.log('不是当天日期')
	console.log(new Date(timestamp).toISOString().slice(0,10));
}
	return Y+M+D+h+m+s;
}
const time = timestampToTime(1620234000000)
console.log(time)

2.2 yyyy-mm-dd或yyyy-MM-dd HH-mm-ss 转为时间戳 

code
var stringTime = '2012-10-12 22:37:33';
//将获取到的时间转换成时间戳
var timestamp = Date.parse(new Date(stringTime));

2.3 中国标准时间转为 yyyy-mm-dd hh-mm-ss 

code
let y = date.getFullYear()
let m = date.getMonth() + 1 
m = m < 10 ? ('0' + m) : m
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
let dateTime= y + '-' + m + '-' + d + ' ' + h + ':' + M + ':' + s

最后成功的完成时间戳的转换!!!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章