微信公众号 - js传入时间戳换算(以前几天、几小时...)
时间:2018-08-18 17:50:07
收藏:0
阅读:618
1 // 获取当前时间戳
2 function timestamps() {
3 return Math.round(new Date().getTime() / 1000).toString()
4 }
5
6 // 距离时间... 传时间戳
7 function timeFormat(timestamps) {
8 timestamps = timestamps * 1000
9 let daySec, dayMin, dayHour, dayS
10 let timeNow = new Date().getTime()
11 let ts = (timeNow - timestamps) / 1000
12 dayS = Math.round(ts / (24 * 60 * 60))
13 dayHour = Math.round(ts / (60 * 60))
14 dayMin = Math.round(ts / 60)
15 daySec = Math.round(ts)
16 if (dayS > 0 && dayS < 2) {
17 return `${dayS} 天以前`
18 } else if (dayS <= 0 && dayHour > 0) {
19 return `${dayHour} 小时以前`
20 } else if (dayHour <= 0 && dayMin > 0) {
21 return `${dayMin} 分钟以前`
22 } else if (dayMin <= 0 && daySec >= 0) {
23 return ‘现在‘
24 } else {
25 let timestamp = new Date()
26 timestamp.setTime(timestamps)
27 return [timestamp.getFullYear(), timestamp.getMonth() + 1, timestamp.getDate()].map(this.formatNumber).join(‘/‘) + ‘ ‘ + [timestamp.getHours(), timestamp.getMinutes()].map(this.formatNumber).join(‘:‘)
28 }
29 }
30
31 function formatNumber(n) {
32 n = n.toString()
33 return n[1] ? n : `0${n}`
34 }
35
36
37 console.log(timestamps(), timeFormat(1534494126));
时间戳转:
评论(0)