2025-04-02 17:32:13 +08:00

66 lines
1.6 KiB
Vue
Raw 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.

<template>
<div class="current-time-warp">{{ currentTime }}</div>
</template>
<script setup>
import { ref, reactive, onMounted, watch, onUnmounted } from 'vue';
let currentTime = ref('');
const formatDateTime = () => {
const now = new Date();
// 获取各部分值
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); // JavaScript中月份从0开始所以需要加1
const day = String(now.getDate()).padStart(2, '0');
// 星期几注意返回的是0周日到6周六
const weekDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][now.getDay()];
const hour = String(now.getHours()).padStart(2, '0');
const minute = String(now.getMinutes()).padStart(2, '0');
const second = String(now.getSeconds()).padStart(2, '0');
// 格式化输出
const formattedDate = `${year}-${month}-${day}\u00A0\u00A0\u00A0 ${weekDay}\u00A0\u00A0\u00A0 ${hour}:${minute}:${second}`;
// console.log(formattedDate);
return formattedDate;
};
let interval = ref(null);
const startTime = () => {
interval.value = setInterval(() => {
currentTime.value = formatDateTime();
}, 1000);
};
const chearTime = () => {
if (interval.value) {
clearInterval(interval.value);
interval.value = null;
}
};
onMounted(() => {
startTime();
});
onUnmounted(() => {
chearTime();
});
defineExpose({
startTime,
chearTime,
});
</script>
<style lang="scss" scoped>
.current-time-warp {
position: fixed;
right: 16px;
top: 24px;
color: #add8f1;
z-index: 2;
}
</style>