日期计算工具函数:getDaysInMonth、getFirstDayOfMonth

📅 2026/7/19 1:11:41
日期计算工具函数:getDaysInMonth、getFirstDayOfMonth
前言在日历组件中日期计算是核心逻辑。“海风日记“的CalendarTab和CalendarYearPage中定义了一系列日期计算工具函数包括获取当月天数、获取第一天是星期几、判断是否今天等。本文将从源码出发深入讲解这些日期计算函数的实现和使用。一、日期计算函数1.1 获取当月天数private getDaysInMonth(year: number, month: number): number { return new Date(year, month 1, 0).getDate() }1.2 获取第一天是星期几private getFirstDayOfMonth(year: number, month: number): number { return new Date(year, month, 1).getDay() // 0星期日 }1.3 判断是否今天private isToday(day: number): boolean { return day this.todayDate this.curMonth this.todayMonth this.curYear this.todayYear }1.4 判断是否有日记private hasDiary(day: number): boolean { const key ${this.curYear}-${String(this.curMonth1).padStart(2,0)}-${String(day).padStart(2,0)} return this.diaryDates.has(key) }二、月份导航private prevMonth() { if (this.curMonth 0) { this.curYear - 1 this.curMonth 11 } else { this.curMonth - 1 } } private nextMonth() { if (this.curMonth 11) { this.curYear 1 this.curMonth 0 } else { this.curMonth 1 } }三、月份名称private getMonthName(month: number): string { return [一月,二月,三月,四月,五月,六月, 七月,八月,九月,十月,十一月,十二月][month] }四、年视图的日期计算年视图的微型日历同样使用这些函数// 微型日历中的日期判断 const isToday day this.todayDate monthIndex this.todayMonth this.curYear this.todayYear const hasDiary this.diaryDates.has( ${this.curYear}-${String(monthIndex1).padStart(2,0)}-${String(day).padStart(2,0)} )五、常见问题5.1 月份显示错误问题月份显示与实际月份差 1 个月。原因Date 对象的月份从 0 开始0一月11十二月。解决方案传入月份时注意month 1或month - 1的转换。总结本文通过“海风日记“的日历功能深入讲解了日期计算函数getDaysInMonth获取当月天数getFirstDayOfMonth获取第一天是星期几isToday判断是否今天hasDiary判断是否有日记月份导航prevMonth / nextMonth下一篇文章将深入讲解今日橙色圆底标记敬请期待。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Date 对象文档Grid 组件文档海风日记项目源码[HarmonyOS 开发者官网](https://atomgit.com/openharmony/docs开源鸿蒙跨平台社区