index.js 1.49 KB
Newer Older
Pan's avatar
Pan committed
1 2 3 4 5 6
/**
 * Created by jiachenpan on 16/11/18.
 */

 export function parseTime(time, cFormat) {
   if (arguments.length === 0) {
Pan's avatar
Pan committed
7
     return null
Pan's avatar
Pan committed
8
   }
Pan's avatar
Pan committed
9 10 11 12
   const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
   let date
   if (typeof time === 'object') {
     date = time
Pan's avatar
Pan committed
13
   } else {
Pan's avatar
Pan committed
14 15
     if (('' + time).length === 10) time = parseInt(time) * 1000
     date = new Date(time)
Pan's avatar
Pan committed
16 17 18 19 20 21 22 23 24
   }
   const formatObj = {
     y: date.getFullYear(),
     m: date.getMonth() + 1,
     d: date.getDate(),
     h: date.getHours(),
     i: date.getMinutes(),
     s: date.getSeconds(),
     a: date.getDay()
Pan's avatar
Pan committed
25
   }
Pan's avatar
Pan committed
26
   const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
Pan's avatar
Pan committed
27 28
     let value = formatObj[key]
     if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
Pan's avatar
Pan committed
29
     if (result.length > 0 && value < 10) {
Pan's avatar
Pan committed
30
       value = '0' + value
Pan's avatar
Pan committed
31
     }
Pan's avatar
Pan committed
32 33 34
     return value || 0
   })
   return time_str
Pan's avatar
Pan committed
35 36 37
 }

 export function formatTime(time, option) {
Pan's avatar
Pan committed
38 39 40
   time = +time * 1000
   const d = new Date(time)
   const now = Date.now()
Pan's avatar
Pan committed
41

Pan's avatar
Pan committed
42
   const diff = (now - d) / 1000
Pan's avatar
Pan committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

   if (diff < 30) {
     return '刚刚'
   } else if (diff < 3600) { // less 1 hour
     return Math.ceil(diff / 60) + '分钟前'
   } else if (diff < 3600 * 24) {
     return Math.ceil(diff / 3600) + '小时前'
   } else if (diff < 3600 * 24 * 2) {
     return '1天前'
   }
   if (option) {
     return parseTime(time, option)
   } else {
     return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
   }
 }