| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- const formatTime = date => {
- const year = date.getFullYear()
- const month = date.getMonth() + 1
- const day = date.getDate()
- const hour = date.getHours()
- const minute = date.getMinutes()
- const second = date.getSeconds()
- return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
- }
- const formatNumber = n => {
- n = n.toString()
- return n[1] ? n : '0' + n
- }
- // 计算时间差
- const handleDate = date => {
- if (typeof date === 'string') {
- date = new Date(date)
- }
- const diffValue = new Date().getTime() - date.getTime()
- if (diffValue < 0) {
- console.log('时间不同步')
- return '刚刚'
- }
- const minute = 1000 * 60
- const hour = minute * 60
- const day = hour * 24
- const minC = diffValue / minute
- const hourC = diffValue / hour
- const dayC = diffValue / day
- let result = ''
- if (parseInt(dayC) > 3) {
- result = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()
- } else if (parseInt(dayC) > 1) {
- result = parseInt(dayC) + '天前'
- } else if (parseInt(dayC) == 1) {
- result = '昨天'
- } else if (hourC >= 1) {
- result = parseInt(hourC) + '小时前'
- } else if (minC >= 3) {
- result = parseInt(minC) + '分钟前'
- } else {
- result = '刚刚'
- }
- return result
- }
- const randomString = len => {
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
- let str = '';
- for (let i = 0; i < len; i++) {
- str += chars[Math.floor(Math.random() * chars.length)]
- }
- return str
- }
- const msgToDb = function (item) {
- item.type = item.type.join()
- item.poster = item.poster.join()
- item.photo = item.photo.join()
- if (item.tag) {
- item.tag = item.tag.join()
- }
- return item
- }
- const dbToMsg = function (item) {
- item.type = item.type.split(',')
- if (item.poster !== '') {
- item.poster = item.poster.split(',')
- } else {
- item.poster = []
- }
- if (item.photo !== '') {
- item.photo = item.photo.split(',')
- } else {
- item.poster = []
- }
- if (item.tag !== '') {
- item.tag = item.tag.split(',')
- } else {
- item.tag = []
- }
- item.publish_time = handleDate(item.publish_time)
- return item
- }
- module.exports = {
- formatTime: formatTime,
- handleDate: handleDate,
- randomString: randomString,
- msgToDb: msgToDb,
- dbToMsg: dbToMsg
- }
|