vue实现带日期星期
实现带日期星期的 Vue 组件
使用 JavaScript 的 Date 对象获取日期和星期
在 Vue 中可以通过 JavaScript 的 Date 对象来获取当前日期和星期几的信息。以下是一个简单的实现方法:
<template>
<div>
{{ currentDate }} {{ currentDay }}
</div>
</template>
<script>
export default {
data() {
return {
currentDate: '',
currentDay: ''
}
},
mounted() {
this.updateDateTime()
},
methods: {
updateDateTime() {
const now = new Date()
const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
this.currentDate = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`
this.currentDay = days[now.getDay()]
}
}
}
</script>
使用第三方库 moment.js 或 day.js
对于更复杂的日期处理,可以使用 moment.js 或 day.js 这样的日期处理库:
<template>
<div>
{{ formattedDate }}
</div>
</template>
<script>
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
export default {
data() {
return {
formattedDate: ''
}
},
mounted() {
this.updateDateTime()
},
methods: {
updateDateTime() {
this.formattedDate = dayjs().format('YYYY年MM月DD日 dddd')
}
}
}
</script>
自动更新的日期时间显示

如果需要日期和时间自动更新,可以添加定时器:
<script>
export default {
data() {
return {
currentDateTime: ''
}
},
mounted() {
this.updateDateTime()
setInterval(this.updateDateTime, 1000)
},
methods: {
updateDateTime() {
const now = new Date()
const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
this.currentDateTime = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日 ${days[now.getDay()]} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`
}
}
}
</script>
国际化日期显示
如果需要支持多种语言的日期显示,可以使用 Vue I18n 配合日期库:

<template>
<div>
{{ $d(new Date(), 'long') }}
</div>
</template>
<script>
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
locale: 'zh-CN',
datetimeFormats: {
'zh-CN': {
long: {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long'
}
},
'en-US': {
long: {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long'
}
}
}
})
export default {
i18n
}
</script>
注意事项
日期格式化时需要注意月份是从0开始的,所以需要加1。星期几的索引从0(星期日)到6(星期六)。
对于生产环境,推荐使用day.js代替moment.js,因为day.js体积更小,API兼容。
如果需要显示24小时制的时间,可以使用toLocaleTimeString方法或日期库的相应格式化选项。






