dapaijizhang3/utils/format.js

116 lines
2.6 KiB
JavaScript
Raw Normal View History

2025-11-20 16:42:59 +08:00
// 格式化工具函数
/**
* 格式化时间戳
* @param {number} timestamp - UNIX时间戳
* @param {string} format - 格式化模板
*/
export function formatTime(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
const date = new Date(timestamp * 1000)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
const seconds = String(date.getSeconds()).padStart(2, '0')
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds)
}
/**
* 格式化金额分转元
* @param {number} amount - 金额
*/
export function formatMoney(amount) {
return (amount / 100).toFixed(2)
}
/**
* 格式化输赢金额
* @param {number} amount - 金额
*/
export function formatWinLoss(amount) {
const yuan = formatMoney(Math.abs(amount))
if (amount > 0) {
return `+${yuan}`
} else if (amount < 0) {
return `-${yuan}`
} else {
return '0.00'
}
}
/**
* 获取相对时间
* @param {number} timestamp - UNIX时间戳
*/
export function getRelativeTime(timestamp) {
const now = Math.floor(Date.now() / 1000)
const diff = now - timestamp
if (diff < 60) {
return '刚刚'
} else if (diff < 3600) {
return `${Math.floor(diff / 60)}分钟前`
} else if (diff < 86400) {
return `${Math.floor(diff / 3600)}小时前`
} else if (diff < 604800) {
return `${Math.floor(diff / 86400)}天前`
} else {
return formatTime(timestamp, 'MM-DD')
}
}
/**
* 获取游戏类型名称
* @param {string} type - 游戏类型
*/
export function getGameTypeName(type) {
const types = {
'mahjong': '麻将',
'poker': '扑克',
'other': '其他'
}
return types[type] || type
}
/**
* 获取牌局状态名称
* @param {string} status - 牌局状态
*/
export function getSessionStatusName(status) {
const statusMap = {
'waiting': '等待中',
'playing': '游戏中',
'paused': '已暂停',
'finished': '已结束',
'cancelled': '已取消'
}
return statusMap[status] || status
}
/**
* 获取牌局状态颜色
* @param {string} status - 牌局状态
*/
export function getSessionStatusColor(status) {
const colorMap = {
'waiting': '#ff9500',
'playing': '#07c160',
'paused': '#999999',
'finished': '#333333',
'cancelled': '#ff3b30'
}
return colorMap[status] || '#666666'
}
export function onMyLoginReady(callback) {
}