日期计算工具函数:getDaysInMonth、getFirstDayOfMonth
2026/7/19 1:11:39 网站建设 项目流程

前言

在日历组件中,日期计算是核心逻辑。“海风日记“的CalendarTabCalendarYearPage中定义了一系列日期计算工具函数,包括获取当月天数、获取第一天是星期几、判断是否今天等。

本文将从源码出发,深入讲解这些日期计算函数的实现和使用。


一、日期计算函数

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.curMonth+1).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(monthIndex+1).padStart(2,'0')}-${String(day).padStart(2,'0')}` )

五、常见问题

5.1 月份显示错误

问题:月份显示与实际月份差 1 个月。

原因:Date 对象的月份从 0 开始(0=一月,11=十二月)。

解决方案:传入月份时注意month + 1month - 1的转换。


总结

本文通过“海风日记“的日历功能,深入讲解了日期计算函数:

  1. getDaysInMonth:获取当月天数
  2. getFirstDayOfMonth:获取第一天是星期几
  3. isToday:判断是否今天
  4. hasDiary:判断是否有日记
  5. 月份导航:prevMonth / nextMonth

下一篇文章将深入讲解今日橙色圆底标记,敬请期待。

如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!


相关资源:

  • Date 对象文档
  • Grid 组件文档
  • 海风日记项目源码
  • [HarmonyOS 开发者官网](https://atomgit.com/openharmony/docs
  • 开源鸿蒙跨平台社区

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询