JS-时间相关的函数封装

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.获取当前时间,代码如下:

 1 //获取当前时间
 2 function getDateTimeNow() {
 3     var time = new Date();
 4     var day = ("0" + time.getDate()).slice(-2)
 5     var month = ("0" + (time.getMonth()+1)).slice(-2)
 6 
 7     var hour = ("0" + time.getHours()).slice(-2)
 8     var minute = ("0" + time.getMinutes()).slice(-2)
 9     var second = ("0" + time.getSeconds()).slice(-2)
10 
11     var today = time.getFullYear() + "-" + (month) + "-" + (day) + " " + (hour) + ":" + (minute) + ":" + second
12     return today
13 }

注意,month必须+1。

上段代码利用字符串的slice(-2)函数,先统一加上0,然后切剩最后两位数字,避开了三元运算符的判断,是比较巧妙的方法。

3.获取半年前、三个月前等过去的时间值,代码如下:

 1 //获取日期时间,time为Date对象
 2 function getDatetimeByDateObj(time) {
 3     var day = ("0" + time.getDate()).slice(-2)
 4     var month = ("0" + (time.getMonth()+1)).slice(-2)
 5 
 6     var hour = ("0" + time.getHours()).slice(-2)
 7     var minute = ("0" + time.getMinutes()).slice(-2)
 8     var second = ("0" + time.getSeconds()).slice(-2)
 9 
10     var datetime = time.getFullYear() + "-" + (month) + "-" + (day) + " " + (hour) + ":" + (minute) + ":" + second
11     return datetime
12 }
13 
14 //获得过去的时间,time的单位为秒
15 function getPastDatetime(time) {
16     var curDate = (new Date()).getTime()
17     time*=1000
18     var pastResult = curDate - time
19     return getDatetimeByDateObj(new Date(pastResult))
20 }

其原理为用Date对象的getTime函数获得当前的毫秒数,然后减去传入的毫秒数,如半年前应传入的time为366/2*24*3600,在函数中乘以1000转成了毫秒数,再相减,然后用差作为参数新建一个Date对象,并解析成普通日期时间。

原文地址:https://www.cnblogs.com/luoyihao/p/11884425.html