
显示当前时间和农历时间
2024年8月10日...小于 1 分钟
显示当前时间和农历时间
安装农历库
npm install lunar-javascript
使用(封装成组件)
<template>
<div :class="d1">{{ formattedDate }}</div>
<div :class="d2">{{ chineseDate }}</div>
</template>
<script>
import { defineComponent, ref, onMounted, onUnmounted, watch } from 'vue';
import { ElCard } from 'element-plus';
import { useThemeStore } from '@/stores/ThemeStore';
import { Lunar } from 'lunar-javascript';
export default defineComponent({
name: 'Clock',
components: {
ElCard,
},
setup() {
const store = useThemeStore()
const d1 = ref(store.icon === 'icon-taiyang' ? 'd1' : 'night-d1');
const d2 = ref(store.icon === 'icon-taiyang' ? 'd2' : 'night-d2');
watch(
() => store.icon,
(newIcon) => {
if (newIcon === 'icon-taiyang') {
d1.value = 'd1';
d2.value = 'd2';
} else if (newIcon === 'icon-yueliang') {
d1.value = 'night-d1';
d2.value = 'night-d2';
}
}
);
const formattedDate = ref('');
const chineseDate = ref('');
const chineseWeekdays = ['日', '一', '二', '三', '四', '五', '六'];
const getChineseZodiacDate = (date) => {
const lunar = Lunar.fromDate(date);
const year = lunar.getYearInGanZhi();
const month = lunar.getMonthInGanZhiExact();
const day = lunar.getDayInGanZhi();
const lunarMonth = lunar.getMonthInChinese();
const lunarDay = lunar.getDayInChinese();
const weekday = chineseWeekdays[date.getDay()];
return `${year}年 ${month}月 ${day}日 ${lunarMonth}月${lunarDay} 星期${weekday}`;
};
const updateDate = () => {
const date = new Date();
formattedDate.value = date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
chineseDate.value = getChineseZodiacDate(date);
};
onMounted(() => {
updateDate();
setInterval(updateDate, 1000);
});
onUnmounted(() => {
clearInterval(updateDate);
});
return {
formattedDate,
chineseDate,
d1,
d2
};
},
});
</script>
<style scoped>
.d1 {
color: #1b2226;
font-size: 14px;
font-weight: 500;
transition: background-color 0.5s;
@media (max-width: 768px) {
display: none;
font-size: 12px;
line-height: 60px;
}
}
.d2 {
margin-top: 5px;
color: #8c8c8c;
font-size: 12px;
transition: background-color 0.5s;
@media (max-width: 768px) {
display: none;
}
}
</style>
你认为这篇文章怎么样?
- 0
- 0
- 0
- 0
- 0
- 0