uniapp打卡日期
uniapp打卡日期实现方法
获取当前日期
使用JavaScript的Date对象获取当前日期,并格式化为需要的字符串形式。可以创建一个工具函数来处理日期格式化:
function formatDate(date) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
}
const today = formatDate(new Date())
存储打卡记录
使用uniapp的本地存储功能保存打卡记录。可以以日期为键,打卡状态为值:
// 打卡
uni.setStorageSync('punchRecords', {
...uni.getStorageSync('punchRecords'),
[today]: true
})
// 检查是否已打卡
const hasPunched = uni.getStorageSync('punchRecords')[today]
日历组件显示
使用uniapp的<calendar>组件或第三方日历插件显示打卡记录。配置标记点来显示已打卡日期:
const markedDates = Object.keys(uni.getStorageSync('punchRecords')).map(date => ({
date,
dots: [{
color: 'green'
}]
}))
服务器同步
如果需要多设备同步,可以将打卡记录上传至服务器:

uni.request({
url: 'https://your-api.com/punch',
method: 'POST',
data: {
date: today,
userId: '123'
}
})
注意事项
- 时区问题:确保服务器和客户端使用相同时区处理日期
- 数据清理:定期清理过期的本地打卡记录
- 用户提示:打卡成功后给予用户反馈提示
完整示例代码
<template>
<view>
<button @click="punchIn">打卡</button>
<calendar :markedDates="markedDates"></calendar>
</view>
</template>
<script>
export default {
data() {
return {
markedDates: []
}
},
methods: {
punchIn() {
const today = this.formatDate(new Date())
const records = uni.getStorageSync('punchRecords') || {}
if (!records[today]) {
uni.setStorageSync('punchRecords', {...records, [today]: true})
this.updateMarkedDates()
uni.showToast({title: '打卡成功'})
} else {
uni.showToast({title: '今日已打卡', icon: 'none'})
}
},
formatDate(date) {
// 同上文formatDate函数
},
updateMarkedDates() {
const records = uni.getStorageSync('punchRecords') || {}
this.markedDates = Object.keys(records).map(date => ({
date,
dots: [{color: 'green'}]
}))
}
},
onLoad() {
this.updateMarkedDates()
}
}
</script>






