From 04e1c9650ca2127b24d67e10f90402ea51001ef7 Mon Sep 17 00:00:00 2001 From: yutent Date: Fri, 17 Nov 2023 13:19:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=97=B6=E9=97=B4=E7=BB=84?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Readme.md | 3 +- src/time/index.js | 96 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 src/time/index.js diff --git a/Readme.md b/Readme.md index 8c32336..39dc69e 100644 --- a/Readme.md +++ b/Readme.md @@ -16,12 +16,13 @@ - wkit 针对`web components`的核心封装库, 以数据驱动, 可以更方便的开发 wc 组件 -### 开发进度 && 计划 (41/55) +### 开发进度 && 计划 (42/56) - [x] `wc-card` 卡片组件 - [x] `wc-space` 间隔组件 - [x] `wc-avatar` 头像组件 - [x] `wc-badge` 徽标组件 +- [x] `wc-time` 时间格式化组件 - [x] `wc-drawer` 抽屉组件 - [x] `wc-collapse` 折叠组件 - [ ] `wc-dropdown` 下拉菜单组件 diff --git a/src/time/index.js b/src/time/index.js new file mode 100644 index 0000000..6539bcf --- /dev/null +++ b/src/time/index.js @@ -0,0 +1,96 @@ +/** + * {} + * @author yutent + * @date 2023/03/21 16:14:10 + */ + +import { css, html, Component } from 'wkit' + +const ONE_MINUTE = 60 * 1000 +const ONE_HOUR = ONE_MINUTE * 60 +const SIX_HOURS = ONE_HOUR * 6 +const ONE_DAY = ONE_HOUR * 24 +const TWO_DAY = ONE_DAY * 2 +const ONE_WEEK = ONE_DAY * 7 +const TODAY = new Date().setHours(0, 0, 0, 0) // 今天凌晨0点整 +const THIS_YEAR = new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0) // 今年 +const LAST_YEAR = new Date(new Date().getFullYear() - 1, 0, 1, 0, 0, 0, 0) // 去年 + +class Time extends Component { + static props = { + stamp: 'num!0' + } + + get #value() { + let n = new Date().setMilliseconds(0) // 现在 + let s = this.stamp || n + let d + + if ((s + '').length === 10) { + s *= 1000 + } + d = new Date(s) + + this.title = d.toLocaleString() + + if (s > n - ONE_MINUTE) { + return '刚刚' + } + if (s > n - ONE_HOUR) { + return `${~~(s / ONE_MINUTE)}分钟前` + } + if (s > n - SIX_HOURS) { + return `${~~(s / ONE_HOUR)}小时前` + } + + if (s >= TODAY - TWO_DAY) { + let h = d.getHours() + let _t = h < 6 ? '凌晨' : h < 12 ? '上午' : h > 18 ? '晚上' : '下午' + + if (s >= TODAY) { + return `${_t}${h % 12}点${d.getMinutes()}分` + } + + if (s >= TODAY - ONE_DAY) { + return `昨天${_t}${h % 12}点` + } + + return `前天${_t}` + } + + if (s >= TODAY - ONE_WEEK) { + return `${~~((n - s) / ONE_DAY)}天前` + } + + if (s > THIS_YEAR) { + return `${d.getMonth() + 1}月${d.getDate()}日` + } + + if (s > LAST_YEAR) { + return `去年${d.getMonth() + 1}月${d.getDate()}日` + } + + return `${d.getFullYear()}年${d.getMonth() + 1}月` + } + + static styles = [ + css` + :host { + display: inline-flex; + font-size: 12px; + color: var(--color-dark-1); + } + time { + -webkit-user-select: none; + user-select: none; + cursor: default; + } + ` + ] + + render() { + return html`` + } +} + +Time.reg('time')