項目開發中常用:獲取當前時間,時間戳轉換標準時間格式

項目開發中經常會遇到時間處理的方法:獲取當前時間,時間戳轉換標準時間格式

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

最後成功的完成時間戳的轉換!!!

 

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