• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一咻儿
博客园    首页    新随笔    联系   管理    订阅  订阅
时间格式转换成指定格式(Vue)
 1 /**
 2  * Parse the time to string
 3  * @param {(Object|string|number)} time
 4  * @param {string} cFormat
 5  * @returns {string | null}
 6  */
 7 export function parseTime(time, cFormat) {
 8   if (arguments.length === 0 || !time) {
 9     return null
10   }
11   const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
12   let date
13   if (typeof time === 'object') {
14     date = time
15   } else {
16     if ((typeof time === 'string')) {
17       if ((/^[0-9]+$/.test(time))) {
18         // support "1548221490638"
19         time = parseInt(time)
20       } else {
21         // support safari
22         // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
23         time = time.replace(new RegExp(/-/gm), '/')
24       }
25     }
26 
27     if ((typeof time === 'number') && (time.toString().length === 10)) {
28       time = time * 1000
29     }
30     date = new Date(time)
31   }
32   const formatObj = {
33     y: date.getFullYear(),
34     m: date.getMonth() + 1,
35     d: date.getDate(),
36     h: date.getHours(),
37     i: date.getMinutes(),
38     s: date.getSeconds(),
39     a: date.getDay()
40   }
41   const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
42     const value = formatObj[key]
43     // Note: getDay() returns 0 on Sunday
44     if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
45     return value.toString().padStart(2, '0')
46   })
47   return time_str
48 }
49 
50 /**
51  * @param {number} time
52  * @param {string} option
53  * @returns {string}
54  */
55 export function formatTime(time, option) {
56   if (('' + time).length === 10) {
57     time = parseInt(time) * 1000
58   } else {
59     time = +time
60   }
61   const d = new Date(time)
62   const now = Date.now()
63 
64   const diff = (now - d) / 1000
65 
66   if (diff < 30) {
67     return '刚刚'
68   } else if (diff < 3600) {
69     // less 1 hour
70     return Math.ceil(diff / 60) + '分钟前'
71   } else if (diff < 3600 * 24) {
72     return Math.ceil(diff / 3600) + '小时前'
73   } else if (diff < 3600 * 24 * 2) {
74     return '1天前'
75   }
76   if (option) {
77     return parseTime(time, option)
78   } else {
79     return (
80       d.getMonth() +
81       1 +
82       '月' +
83       d.getDate() +
84       '日' +
85       d.getHours() +
86       '时' +
87       d.getMinutes() +
88       '分'
89     )
90   }
91 }
const start = new Date()
formatTime(start, '{y}-{m}-{d}', 0)


 

posted on 2022-03-07 20:08  一咻儿  阅读(642)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3