欢迎光临
我们一直在努力

在线时间戳转换工具:基于Vue 3 + TypeScript的精准实现

在软件开发、日志分析和跨时区协作中,时间戳与可读日期时间的相互转换是一项基础且高频的需求。Unix时间戳作为计算机系统通用的时间表示方式,对人类阅读极不友好。本文介绍一款基于Vue 3和TypeScript实现的在线时间戳转换工具,支持实时显示当前时间戳、双向转换、毫秒/秒级精度切换,并提供直观的交互体验。

在线体验:https://www.52iis.com/timetran/

工具概览

本工具提供全方位的时间戳处理功能,核心特性包括:

  • 实时当前时间戳:动态显示当前毫秒级时间戳,支持暂停/刷新

  • 时间戳转日期:输入毫秒或秒级时间戳,转换为标准日期时间

  • 日期转时间戳:选择日期时间,转换为毫秒或秒级时间戳

  • 双精度支持:毫秒(13位)和秒(10位)时间戳一键切换

  • 一键复制:所有结果均支持复制,提升使用效率

  • 实时更新控制:可暂停或恢复当前时间戳的自动刷新

所有转换在浏览器本地完成,确保时间数据的准确性和隐私性。

技术实现

以下为工具的核心Vue组件代码,展示了如何使用Vue 3的组合式API和TypeScript实现完整的时间戳转换功能:

<script setup lang="ts">
import { onMounted, onUnmounted, reactive } from 'vue'
import { VideoPause, VideoPlay, CopyDocument } from '@element-plus/icons-vue'
import { Jh_getTimeStamp, Jh_timeStampToTime, Jh_convertTimeStamp } from '@/utils/time'
import DetailHeader from '@/components/Layout/DetailHeader/DetailHeader.vue'
import ToolDetail from '@/components/Layout/ToolDetail/ToolDetail.vue'
import { copy } from '@/utils/string'

// 响应式状态管理
const info = reactive({
title: "⏱️ 时间戳转换",
nowTime: Jh_getTimeStamp(), // 当前时间戳
isPlay: true, // 定时器状态
waitTimeStamp: Jh_getTimeStamp(), // 待转换的时间戳
tranTimeStamp: 0, // 转换后的时间戳
waitDate: Jh_timeStampToTime(Jh_getTimeStamp(), '{y}-{m}-{d} {h}:{i}:{s}'), // 待转换的日期时间
tranDate: '', // 转换后的日期时间
chooseTranStampOption: '0', // 时间戳转日期时的精度选项
chooseTranDateOption: '0', // 日期转时间戳时的精度选项
tranOptions: [
{ value: '0', label: '毫秒(ms)' },
{ value: '1', label: '秒(s)' }
]
})

let timer: number | null = null

/**
* 启动定时器:每秒更新当前时间戳
*/
const start = () => {
if (!timer) {
timer = setInterval(() => {
info.nowTime = Jh_getTimeStamp()
}, 1000) as unknown as number
}
}

/**
* 停止定时器
*/
const stop = () => {
if (timer) {
clearInterval(timer)
timer = null
}
}

// 组件挂载时启动定时器
onMounted(() => {
start()
})

// 组件卸载时清理定时器
onUnmounted(() => {
stop()
})

/**
* 切换定时器状态(播放/暂停)
*/
const isPlayChange = () => {
info.isPlay = !info.isPlay
if (info.isPlay) {
start()
} else {
stop()
}
}

/**
* 时间与时间戳相互转换
* @param type 'toStamp' – 日期转时间戳 | 'toDate' – 时间戳转日期
*/
const timeTran = (type: string) => {
if (type === 'toStamp') {
// 日期转时间戳
const timestamp = Jh_convertTimeStamp(info.waitDate)
info.tranTimeStamp = info.chooseTranStampOption === '0' ? timestamp : Math.floor(timestamp / 1000)
} else {
// 时间戳转日期
// 确保输入为数字
if (typeof info.waitTimeStamp === 'string') {
info.waitTimeStamp = parseInt(info.waitTimeStamp as string)
}
// 根据选择的精度处理时间戳
const timestamp = info.chooseTranDateOption === '0'
? info.waitTimeStamp
: info.waitTimeStamp * 1000
info.tranDate = Jh_timeStampToTime(timestamp, '{y}-{m}-{d} {h}:{i}:{s}')
}
}

// 复制当前时间戳
const copyRes = async () => {
copy(String(info.nowTime))
}

// 复制转换后的日期
const copyTranDate = async () => {
if (info.tranDate) copy(info.tranDate)
}

// 复制转换后的时间戳
const copyTranTimeStamp = async () => {
if (info.tranTimeStamp) copy(String(info.tranTimeStamp))
}
</script>

<template>
<div class="flex flex-col flex-1 mt-3 ml-4">
<DetailHeader :title="info.title" />

<!– 主操作区 –>
<div class="flex flex-col p-4 bg-white rounded-2xl">
<!– 当前时间戳行 –>
<div class="flex items-center flex-wrap gap-2">
<el-text class="w-12" size="large">现在</el-text>
<el-button link @click="copyRes()">
{{ info.nowTime }}
<el-icon class="ml-1"><CopyDocument /></el-icon>
</el-button>
<el-button
v-if="info.isPlay"
type="danger"
link
class="flex items-center"
@click="isPlayChange()"
>
<el-icon class="mr-1"><VideoPlay /></el-icon>停止
</el-button>
<el-button
v-else
type="primary"
link
class="flex items-center"
@click="isPlayChange()"
>
<el-icon class="mr-1"><VideoPause /></el-icon>开始
</el-button>
</div>

<!– 时间戳转日期行 –>
<div class="flex items-center flex-wrap gap-2 mt-4">
<el-text class="w-12">时间戳</el-text>
<el-input
v-model="info.waitTimeStamp"
class="w-60"
placeholder="请输入时间戳"
:min="0"
type="number"
>
<template #prepend>
<el-select v-model="info.chooseTranDateOption" class="w-20">
<el-option
v-for="item in info.tranOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</template>
</el-input>
<el-button @click="timeTran('toDate')">转日期</el-button>
<el-input
v-model="info.tranDate"
class="w-72"
placeholder="转换后的日期"
readonly
>
<template #append>
<el-button
:icon="CopyDocument"
@click="copyTranDate()"
:disabled="!info.tranDate"
/>
</template>
</el-input>
</div>

<!– 日期转时间戳行 –>
<div class="flex items-center flex-wrap gap-2 mt-4">
<el-text class="w-12">日期</el-text>
<el-date-picker
v-model="info.waitDate"
type="datetime"
class="w-60"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
placeholder="选择日期时间"
/>
<el-button @click="timeTran('toStamp')">转时间戳</el-button>
<el-input
v-model="info.tranTimeStamp"
class="w-72"
placeholder="转换后的时间戳"
readonly
>
<template #prepend>
<el-select v-model="info.chooseTranStampOption" class="w-20">
<el-option
v-for="item in info.tranOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</template>
<template #append>
<el-button
:icon="CopyDocument"
@click="copyTranTimeStamp()"
:disabled="!info.tranTimeStamp"
/>
</template>
</el-input>
</div>
</div>

<!– 功能说明 –>
<ToolDetail title="工具描述">
<el-text>
<p class="mb-2">
时间戳(Unix Timestamp)是从1970年1月1日(UTC/GMT午夜)开始所经过的秒数(不考虑闰秒),
是计算机系统中广泛使用的时间表示方式。本工具提供时间戳与可读日期时间的双向转换:
</p>
<ul class="list-disc pl-5 space-y-1">
<li><strong>实时当前时间戳</strong>:动态显示当前毫秒级时间戳,可暂停刷新</li>
<li><strong>时间戳转日期</strong>:支持毫秒(13位)和秒(10位)两种精度输入</li>
<li><strong>日期转时间戳</strong>:可选择输出毫秒或秒级时间戳</li>
<li><strong>一键复制</strong>:所有结果均可快速复制使用</li>
</ul>
</el-text>
</ToolDetail>

<ToolDetail title="核心工具函数">
<el-text>
<pre class="bg-gray-50 p-3 rounded-lg overflow-x-auto text-sm">
// 获取当前毫秒级时间戳
export function Jh_getTimeStamp(): number {
return new Date().getTime()
}

// 时间戳转指定格式日期
export function Jh_timeStampToTime(
time: string | number | Date,
cFormat: string
): string {
const date = new Date(typeof time === 'number' && time.toString().length === 10
? time * 1000 : time)
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
w: date.getDay()
}
return cFormat.replace(/{(y|m|d|h|i|s|w)+}/g, (result, key) => {
let value = formatObj[key]
if (key === 'w') return ['日', '一', '二', '三', '四', '五', '六'][value]
if (result.length > 0 && value < 10) value = '0' + value
return value || 0
})
}

// 日期字符串转时间戳
export function Jh_convertTimeStamp(time: string): number {
// 兼容iOS格式(将"-"替换为"/")
let newTime = time.replace(/-/g, '/')
// 处理中文日期格式
newTime = newTime.replace(/年|月/g, '/').replace(/日/g, '')
// 补全缺失的部分
if (newTime.length === 4) newTime += '/01/01 00:00:00'
if (newTime.length === 7) newTime += '/01 00:00:00'
if (newTime.length === 10) newTime += ' 00:00:00'
if (newTime.length === 16) newTime += ':00'
return Date.parse(newTime)
}
</pre>
</el-text>
</ToolDetail>

<ToolDetail title="使用场景">
<el-text>
<ul class="list-disc pl-5 space-y-1">
<li><strong>开发调试</strong>:查看API返回的时间戳对应的具体时间</li>
<li><strong>日志分析</strong>:将日志中的时间戳转换为可读格式</li>
<li><strong>数据库查询</strong>:生成特定时间点的时间戳用于数据筛选</li>
<li><strong>跨时区协作</strong>:统一时间表示,避免时区混淆</li>
<li><strong>定时任务</strong>:计算未来某个时间点的时间戳</li>
</ul>
</el-text>
</ToolDetail>

<ToolDetail title="技术要点">
<el-text>
<ul class="list-disc pl-5 space-y-1">
<li><strong>响应式定时器</strong>:使用Vue 3的onMounted/onUnmounted生命周期管理定时器,避免内存泄漏</li>
<li><strong>TypeScript类型保障</strong>:为所有函数参数和返回值定义类型,提升代码可靠性</li>
<li><strong>iOS兼容性</strong>:日期转换时自动将"-"替换为"/",解决iOS中Date.parse的兼容问题</li>
<li><strong>精度自适应</strong>:根据输入长度自动判断秒级时间戳并转换</li>
<li><strong>组件化设计</strong>:复用DetailHeader、ToolDetail等通用组件</li>
</ul>
</el-text>
</ToolDetail>
</div>
</template>

<style scoped>
.w-60 {
width: 240px;
}

.w-72 {
width: 280px;
}

@media (max-width: 640px) {
.w-60, .w-72 {
width: 100%;
}

:deep(.el-select) {
width: 100%;
}
}
</style>

核心工具函数深度解析

1. 获取当前时间戳

export function Jh_getTimeStamp(): number {
return new Date().getTime() // 返回毫秒级时间戳(13位)
}

设计考量:

  • 使用 getTime() 而非 Date.parse(new Date()),性能更优

  • 返回毫秒级精度,符合JavaScript标准

  • 13位数字,与Unix秒级时间戳(10位)区分

2. 时间戳转日期  

export function Jh_timeStampToTime(
time: string | number | Date,
cFormat: string
): string {
if (arguments.length === 0) return ''

let date: Date
if (typeof time === 'object') {
date = time as Date
} else {
// 自动识别秒级时间戳(10位)并转换
if (('' + time).length === 10) time = parseInt(time as string) * 1000
date = new Date(time)
}

const formatObj: any = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
w: date.getDay()
}

// 智能格式化
return cFormat.replace(/{(y|m|d|h|i|s|w)+}/g, (result, key) => {
let value = formatObj[key]
if (key === 'w') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value // 自动补零
}
return value || 0
})
}

核心特性:

  • 自动识别秒级(10位)和毫秒级(13位)时间戳

  • 支持灵活的自定义格式,如 {y}年{m}月{d}日 {h}:{i}:{s}

  • 星期自动转换为中文显示

  • 数字自动补零,如 03 而非 3

3. 日期转时间戳

export function Jh_convertTimeStamp(time: string): number {
// 兼容iOS:将"-"替换为"/"
let newTime = time.replace(/-/g, '/')

// 处理中文日期格式
newTime = newTime.replace(/年|月/g, '/').replace(/日/g, '')

// 智能补全缺失的时间部分
if (newTime.length === 4) { // 仅年份
newTime = newTime + '/01/01 00:00:00'
}
if (newTime.length === 7) { // 年月
newTime = newTime + '/01 00:00:00'
}
if (newTime.length === 10) { // 年月日
newTime = newTime + ' 00:00:00'
}
if (newTime.length === 16) { // 年月日 时:分
newTime = newTime + ':00'
}

return Date.parse(newTime)
}

设计亮点:

  • iOS兼容性:将日期分隔符从 – 替换为 /,避免Safari中 Date.parse 返回NaN

  • 中文支持:自动处理 2023年12月25日 格式

  • 智能补全:用户可输入不完整的日期,工具自动补全为当日午夜

功能特点详解

1. 实时时间戳的动态控制

工具提供当前时间戳的实时显示,并支持暂停/刷新:

// 定时器管理
const start = () => {
if (!timer) {
timer = setInterval(() => {
info.nowTime = Jh_getTimeStamp()
}, 1000)
}
}

应用场景:

  • 需要固定时间戳进行测试时,可暂停更新

  • 观察时间戳每秒变化,理解其递增特性

2. 双精度双向转换

工具在界面中提供了两个精度选择器:

  • 时间戳转日期:选择输入的时间戳是毫秒还是秒

  • 日期转时间戳:选择输出毫秒还是秒级时间戳

// 精度处理逻辑
if (type === 'toStamp') {
const timestamp = Jh_convertTimeStamp(info.waitDate)
info.tranTimeStamp = info.chooseTranStampOption === '0'
? timestamp // 毫秒
: Math.floor(timestamp / 1000) // 秒
} else {
const timestamp = info.chooseTranDateOption === '0'
? info.waitTimeStamp // 毫秒
: info.waitTimeStamp * 1000 // 秒
info.tranDate = Jh_timeStampToTime(timestamp, '{y}-{m}-{d} {h}:{i}:{s}')
}

3. 一键复制优化

每个结果都配有复制按钮,并自动处理数据类型:

const copyRes = async () => {
copy(String(info.nowTime)) // 确保数字转为字符串
}

性能与用户体验优化

1. 定时器生命周期管理

onMounted(() => start())
onUnmounted(() => stop())

确保组件销毁时定时器被清理,避免内存泄漏。

2. 响应式布局

@media (max-width: 640px) {
.w-60, .w-72 {
width: 100%; /* 移动端自适应 */
}
}

3. 输入验证与容错

  • 时间戳输入框限制为数字类型

  • 日期选择器提供可视化选择,避免格式错误

  • 复制按钮在无结果时自动禁用

应用场景案例

场景一:API调试

开发者在调试接口时,返回的时间戳为 1735660800000,通过工具可快速得知对应时间为 2025-01-01 00:00:00。

场景二:日志分析

系统日志记录错误时间为 1704038400(秒级时间戳),使用工具转换为 2024-01-01 00:00:00,便于定位问题。

场景三:定时任务配置

需要设置一个定时任务在2025年3月1日零点执行,通过日期转时间戳功能获得毫秒级时间戳 1740787200000,可直接用于代码配置。

场景四:跨时区协作

海外团队提供的时间戳 1704038400(UTC时间),通过工具转换为北京时间 2024-01-01 08:00:00,避免时区误解。

技术栈总结

技术用途
Vue 3 Composition API 响应式状态管理与生命周期控制
TypeScript 类型约束与代码健壮性保障
Element Plus UI组件库,提供日期选择器、按钮等
CSS Flex/Grid 响应式布局实现
Web Crypto (备用)确保时间计算的准确性

结语

这款时间戳转换工具通过Vue 3的响应式系统和TypeScript的类型保障,实现了一个功能全面、体验流畅的在线工具。其核心价值在于:

  • 准确性:严格遵循Unix时间戳标准,毫秒/秒级精度自动识别

  • 易用性:双向转换、精度切换、一键复制,操作路径最短

  • 可靠性:完善的错误处理和兼容性适配(特别是iOS)

  • 教育性:实时展示时间戳变化,帮助理解时间表示原理

无论是日常开发、系统运维还是学习研究,这款工具都能提供高效可靠的服务。代码结构清晰,功能模块化,便于后续扩展和维护,是Vue 3和TypeScript实战应用的典范。


在线体验:https://www.52iis.com/timetran/ 项目源码:该工具为开源项目,如需查看更多技术细节或参与贡献,可访问项目GitHub仓库

赞(0)
未经允许不得转载:171主机测评 » 在线时间戳转换工具:基于Vue 3 + TypeScript的精准实现
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址