format-utils.uts
2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* 格式化工具函数(系统级)
* 包含文本处理、时间格式化等通用功能
*/
/**
* 判断文本是否为空或无效值
* 后端偶发将缺省序列化为字符串 "null"/"undefined";仅用于展示判断
*/
export function isBlankDisplayText(text: string | null): boolean {
if (text == null) {
return true
}
const t = text.trim()
if (t.length == 0) {
return true
}
const lower = t.toLowerCase()
return lower == 'null' || lower == 'undefined'
}
/**
* 卡片信息区:无有效文案时统一展示占位符
*/
export function textOrDash(text: string | null): string {
if (isBlankDisplayText(text)) {
return '--'
}
return text as string
}
/**
* 格式化电话号码:3-4-4 格式
*/
export function formatPhone(phone: string | null): string {
if (phone == null || phone == '') {
return ''
}
const p = phone as string
if (isBlankDisplayText(p)) {
return ''
}
const s = p.replace(/\s/g, '')
if (s.length >= 11) {
return s.substring(0, 3) + ' ' + s.substring(3, 7) + ' ' + s.substring(7, 11)
}
return p
}
/**
* 格式化时间戳为日期时间字符串:yyyy.MM.dd HH:mm:ss
*/
export function formatTimestamp(ts: number | null): string {
if (ts == null || ts <= 0) {
return ''
}
const d = new Date(ts)
const y = d.getFullYear()
const m = (d.getMonth() + 1).toString().padStart(2, '0')
const day = d.getDate().toString().padStart(2, '0')
const h = d.getHours().toString().padStart(2, '0')
const min = d.getMinutes().toString().padStart(2, '0')
const sec = d.getSeconds().toString().padStart(2, '0')
return `${y}.${m}.${day} ${h}:${min}:${sec}`
}
/**
* 格式化时间戳为日期字符串:yyyy-MM-dd
*/
export function formatDateOnly(ts: number | null): string {
if (ts == null || ts <= 0) {
return ''
}
const d = new Date(ts)
const y = d.getFullYear()
const m = (d.getMonth() + 1).toString().padStart(2, '0')
const day = d.getDate().toString().padStart(2, '0')
return `${y}-${m}-${day}`
}
/**
* 格式化类日期字段(支持字符串、数字时间戳)
* 入参可为 null(JSON 缺字段),避免调用方 `as any` 在 Kotlin 侧触发非空 Any 强转 NPE
*/
export function formatDateTimeLike(value: any | null): string {
if (value == null) {
return ''
}
if (typeof value == 'string') {
if (isBlankDisplayText(value)) {
return ''
}
return value
}
if (typeof value == 'number') {
return formatTimestamp(value)
}
const s = `${value}`
if (isBlankDisplayText(s)) {
return ''
}
const n = parseFloat(s)
if (!isNaN(n) && n > 0) {
return formatTimestamp(n)
}
return s
}