guangchao.xu | 070005a | 2020-12-07 09:56:40 +0800 | [diff] [blame] | 1 | import timeFormat from '../../libs/function/timeFormat.js'; |
| 2 | |
| 3 | /** |
| 4 | * 时间戳转为多久之前 |
| 5 | * @param String timestamp 时间戳 |
| 6 | * @param String | Boolean format 如果为时间格式字符串,超出一定时间范围,返回固定的时间格式; |
| 7 | * 如果为布尔值false,无论什么时间,都返回多久以前的格式 |
| 8 | */ |
| 9 | function timeFrom(timestamp = null, format = 'yyyy-mm-dd') { |
| 10 | if (timestamp == null) timestamp = Number(new Date()); |
| 11 | timestamp = parseInt(timestamp); |
| 12 | // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位) |
| 13 | if (timestamp.toString().length == 10) timestamp *= 1000; |
| 14 | var timer = (new Date()).getTime() - timestamp; |
| 15 | timer = parseInt(timer / 1000); |
| 16 | // 如果小于5分钟,则返回"刚刚",其他以此类推 |
| 17 | let tips = ''; |
| 18 | switch (true) { |
| 19 | case timer < 300: |
| 20 | tips = '刚刚'; |
| 21 | break; |
| 22 | case timer >= 300 && timer < 3600: |
| 23 | tips = parseInt(timer / 60) + '分钟前'; |
| 24 | break; |
| 25 | case timer >= 3600 && timer < 86400: |
| 26 | tips = parseInt(timer / 3600) + '小时前'; |
| 27 | break; |
| 28 | case timer >= 86400 && timer < 2592000: |
| 29 | tips = parseInt(timer / 86400) + '天前'; |
| 30 | break; |
| 31 | default: |
| 32 | // 如果format为false,则无论什么时间戳,都显示xx之前 |
| 33 | if(format === false) { |
| 34 | if(timer >= 2592000 && timer < 365 * 86400) { |
| 35 | tips = parseInt(timer / (86400 * 30)) + '个月前'; |
| 36 | } else { |
| 37 | tips = parseInt(timer / (86400 * 365)) + '年前'; |
| 38 | } |
| 39 | } else { |
| 40 | tips = timeFormat(timestamp, format); |
| 41 | } |
| 42 | } |
| 43 | return tips; |
| 44 | } |
| 45 | |
| 46 | export default timeFrom; |