You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用date-fns实现Angular 9项目当年周数下拉列表功能

Angular 9 + date-fns 实现当年周数下拉选择列表方案

前置依赖检查

  • 确保项目安装了兼容Angular9的date-fns 2.x版本,未安装可执行以下命令:
    npm install date-fns@2.30.0 --save
  • 确保功能所属模块已经导入FormsModule,否则ngModel双向绑定会失效

组件逻辑实现(xxx.component.ts)

首先导入需要的date-fns工具方法:

import { Component, OnInit } from '@angular/core';
import { getISOWeeksInYear, startOfYear, eachWeekOfInterval, endOfWeek, format, getISOWeek, getYear } from 'date-fns';

组件类内部实现周列表生成逻辑:

@Component({
  selector: 'app-week-selector',
  templateUrl: './week-selector.component.html',
  styleUrls: ['./week-selector.component.css']
})
export class WeekSelectorComponent implements OnInit {
  // 下拉绑定值
  selectedWeek: number;
  // 下拉选项列表
  weekOptions: { value: number, label: string }[] = [];

  ngOnInit(): void {
    this.generateWeekOptions();
  }

  private generateWeekOptions(): void {
    const currentDate = new Date();
    const yearStart = startOfYear(currentDate);
    const yearEnd = new Date(getYear(currentDate), 11, 31);

    // 生成当年所有周的起始日期
    const weeks = eachWeekOfInterval({
      start: yearStart,
      end: yearEnd
    }, {
      weekStartsOn: 1 // 配置周从周一开始,若需要周日开始改为0即可
    });

    // 组装下拉选项,格式和效果图一致
    this.weekOptions = weeks.map(weekStart => {
      const weekNum = getISOWeek(weekStart);
      const weekEnd = endOfWeek(weekStart, { weekStartsOn: 1 });
      return {
        value: weekNum,
        label: `第${weekNum}周(${format(weekStart, 'yyyy-MM-dd')} ~ ${format(weekEnd, 'yyyy-MM-dd')})`
      };
    });
  }
}

模板实现(xxx.component.html)

用Angular原生select组件渲染下拉列表即可:

<select [(ngModel)]="selectedWeek" class="week-select">
  <option *ngFor="let option of weekOptions" [value]="option.value">
    {{ option.label }}
  </option>
</select>

适配说明

  • 如需自定义日期显示格式,直接修改format方法的第二个参数即可,支持yyyy年MM月dd日等中文格式
  • 若要切换其他年份的周列表,仅需要把generateWeekOptions方法里的currentDate替换为对应年份的日期对象,重新调用方法即可生成对应年份的周选项
  • 该实现完全符合ISO周数规则,无跨年周显示异常的问题

内容的提问来源于stack exchange,提问作者Lady_Angular

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 16:48:03