Files
2025-10-05 14:03:21 +08:00

44 lines
1.4 KiB
TypeScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export const formatTime = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return (
[year, month, day].map(formatNumber).join('/') +
' ' +
[hour, minute, second].map(formatNumber).join(':')
)
}
const formatNumber = (n: number) => {
const s = n.toString()
return s[1] ? s : '0' + s
}
// px 和 rpx 转换工具
export function toRpx(value: number, designWidth: number = 750): string {
// 核心转换公式: (value / designWidth) * 750
// 如果设计稿是750公式简化为 (value / 750) * 750 = value
const result = (value / designWidth) * 750;
return `${result.toFixed(2)}rpx`; // 保留两位小数避免精度问题,也可用 toFixed(0) 取整
}
/**
* 将rpx字符串转换回数值用于反向计算等特殊场景
* @param rpxStr rpx字符串例如'100rpx'
* @param designWidth 设计稿宽度单位px默认为750
* @returns 转换后的数值
*/
export function fromRpx(rpxStr: string, designWidth: number = 750): number {
const num = parseFloat(rpxStr);
if (isNaN(num)) {
console.warn(`fromRpx: 无法从"${rpxStr}"中解析出数值`);
return 0;
}
// 核心转换公式: (num / 750) * designWidth
const result = (num / 750) * designWidth;
return result;
}