66 lines
1.6 KiB
Vue
Raw Normal View History

2025-03-17 17:34:32 +08:00
<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);
2025-03-21 16:48:39 +08:00
interval.value = null;
2025-03-17 17:34:32 +08:00
}
};
2025-03-21 16:48:39 +08:00
onMounted(() => {
2025-04-02 17:32:13 +08:00
startTime();
2025-03-21 16:48:39 +08:00
});
onUnmounted(() => {
2025-04-02 17:32:13 +08:00
chearTime();
2025-03-21 16:48:39 +08:00
});
2025-03-17 17:34:32 +08:00
defineExpose({
startTime,
chearTime,
});
</script>
<style lang="scss" scoped>
.current-time-warp {
position: fixed;
right: 16px;
2025-03-21 16:48:39 +08:00
top: 24px;
2025-03-17 17:34:32 +08:00
color: #add8f1;
z-index: 2;
}
</style>