1.用JS把时间戳转换为时间,代码如下:
//时间戳转换为时间
function timestampToTime(timestamp,number) {
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())
var res = Y + M + D + h + m + s
if(number){
return res.substring(0,number)
}
return res
}
注意,时间戳为10位的在转换前需先将timestamp*1000,时间戳为13位的话不需乘1000。这里的number可传可不传,用于个性化截断时间输出。
2.获取当前时间,代码如下:
//获取当前时间
function getDateTimeNow() {
var time = new Date();
var day = ("0" + time.getDate()).slice(-2)
var month = ("0" + (time.getMonth()+1)).slice(-2)
var hour = ("0" + time.getHours()).slice(-2)
var minute = ("0" + time.getMinutes()).slice(-2)
var second = ("0" + time.getSeconds()).slice(-2)
var today = time.getFullYear() + "-" + (month) + "-" + (day) + " " + (hour) + ":" + (minute) + ":" + second
return today
}
注意,month必须+1。
上段代码利用字符串的slice(-2)函数,先统一加上0,然后切剩最后两位数字,避开了三元运算符的判断,是比较巧妙的方法。
3.获取半年前、三个月前等过去的时间值,代码如下:
//获取日期时间,time为Date对象
function getDatetimeByDateObj(time) {
var day = ("0" + time.getDate()).slice(-2)
var month = ("0" + (time.getMonth()+1)).slice(-2)
var hour = ("0" + time.getHours()).slice(-2)
var minute = ("0" + time.getMinutes()).slice(-2)
var second = ("0" + time.getSeconds()).slice(-2)
var datetime = time.getFullYear() + "-" + (month) + "-" + (day) + " " + (hour) + ":" + (minute) + ":" + second
return datetime
}
//获得过去的时间,time的单位为秒
function getPastDatetime(time) {
var curDate = (new Date()).getTime()
time*=1000
var pastResult = curDate - time
return getDatetimeByDateObj(new Date(pastResult))
}
其原理为用Date对象的getTime函数获得当前的毫秒数,然后减去传入的毫秒数,如半年前应传入的time为366/2*24*3600,在函数中乘以1000转成了毫秒数,再相减,然后用差作为参数新建一个Date对象,并解析成普通日期时间。
4.时间字符串(如2020-08-19 10:09)转时间戳
//时间字符串(如2020-08-19 10:09)转时间戳
function timeStrToTimestamp(timeStr){
return new Date(timeStr).getTime() / 1000
}