DatePicker日期选择框

输入或选择日期的控件。

何时使用#

当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。

单独引入此组件#

想要了解更多关于单独引入组件的内容,可以在快速上手页面进行查看。

import { NzDatePickerModule } from 'ng-zorro-antd/date-picker';

代码演示




~

最简单的用法,在浮层中可以选择或者输入日期。

expand codeexpand code
import { Component } from '@angular/core';
import getISOWeek from 'date-fns/get_iso_week';
import { en_US, zh_CN, NzI18nService } from 'ng-zorro-antd/i18n';

@Component({
  selector: 'nz-demo-date-picker-basic',
  template: `
    <nz-date-picker [(ngModel)]="date" (ngModelChange)="onChange($event)"></nz-date-picker>
    <br />
    <nz-month-picker
      [(ngModel)]="date"
      (ngModelChange)="onChange($event)"
      nzPlaceHolder="Select month"
    ></nz-month-picker>
    <br />
    <nz-year-picker [(ngModel)]="date" (ngModelChange)="onChange($event)" nzPlaceHolder="Select year"></nz-year-picker>
    <br />
    <nz-range-picker [(ngModel)]="dateRange" (ngModelChange)="onChange($event)"></nz-range-picker>
    <br />
    <nz-week-picker [(ngModel)]="date" (ngModelChange)="getWeek($event)" nzPlaceHolder="Select week"></nz-week-picker>
    <br />
    <button nz-button nzType="default" (click)="changeLanguage()">Switch language for all pickers</button>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-year-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerBasicComponent {
  date = null; // new Date();
  dateRange = []; // [ new Date(), addDays(new Date(), 3) ];
  isEnglish = false;

  constructor(private i18n: NzI18nService) {}

  onChange(result: Date): void {
    console.log('onChange: ', result);
  }

  getWeek(result: Date): void {
    console.log('week: ', getISOWeek(result));
  }

  changeLanguage(): void {
    this.i18n.setLocale(this.isEnglish ? zh_CN : en_US);
    this.isEnglish = !this.isEnglish;
  }
}




~

三种大小的输入框,若不设置,则为 default

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-date-picker-size',
  template: `
    <nz-radio-group [(ngModel)]="size">
      <label nz-radio-button nzValue="large">large</label>
      <label nz-radio-button nzValue="default">default</label>
      <label nz-radio-button nzValue="small">small</label>
    </nz-radio-group>
    <br /><br />
    <nz-date-picker [nzSize]="size"></nz-date-picker>
    <br />
    <nz-month-picker [nzSize]="size" nzPlaceHolder="Select Month"></nz-month-picker>
    <br />
    <nz-range-picker [nzSize]="size"></nz-range-picker>
    <br />
    <nz-week-picker [nzSize]="size" nzPlaceHolder="Select Week"></nz-week-picker>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerSizeComponent {
  size = 'default';
}


~

选择框的不可用状态。

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-date-picker-disabled',
  template: `
    <nz-date-picker nzDisabled></nz-date-picker>
    <br />
    <nz-month-picker nzDisabled></nz-month-picker>
    <br />
    <nz-range-picker nzDisabled></nz-range-picker>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerDisabledComponent {}

RangePicker 无法满足业务需求时,可以使用两个 DatePicker 实现类似的功能。

  • 通过设置 nzDisabledDate 方法,来约束开始和结束日期。
  • 通过 nzOpennzOnOpenChange 来优化交互。
expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-date-picker-start-end',
  template: `
    <nz-date-picker
      [nzDisabledDate]="disabledStartDate"
      nzShowTime
      nzFormat="yyyy-MM-dd HH:mm:ss"
      [(ngModel)]="startValue"
      nzPlaceHolder="Start"
      (ngModelChange)="onStartChange($event)"
      (nzOnOpenChange)="handleStartOpenChange($event)"
    >
    </nz-date-picker>
    <nz-date-picker
      [nzDisabledDate]="disabledEndDate"
      nzShowTime
      nzFormat="yyyy-MM-dd HH:mm:ss"
      [(ngModel)]="endValue"
      nzPlaceHolder="End"
      [nzOpen]="endOpen"
      (ngModelChange)="onEndChange($event)"
      (nzOnOpenChange)="handleEndOpenChange($event)"
    >
    </nz-date-picker>
  `,
  styles: [
    `
      nz-date-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerStartEndComponent {
  startValue: Date | null = null;
  endValue: Date | null = null;
  endOpen = false;

  disabledStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.endValue) {
      return false;
    }
    return startValue.getTime() > this.endValue.getTime();
  };

  disabledEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.startValue) {
      return false;
    }
    return endValue.getTime() <= this.startValue.getTime();
  };

  onStartChange(date: Date): void {
    this.startValue = date;
  }

  onEndChange(date: Date): void {
    this.endValue = date;
  }

  handleStartOpenChange(open: boolean): void {
    if (!open) {
      this.endOpen = true;
    }
    console.log('handleStartOpenChange', open, this.endOpen);
  }

  handleEndOpenChange(open: boolean): void {
    console.log(open);
    this.endOpen = open;
  }
}
~

使用 nzDateRender 可以自定义日期单元格的内容和样式。

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-date-picker-date-render',
  template: `
    <nz-date-picker [nzDateRender]="tplRender"></nz-date-picker>
    <nz-range-picker [nzDateRender]="tplRender"></nz-range-picker>

    <ng-template #tplRender let-current>
      <div class="ant-calendar-date" [class.border]="current.getDate() === 1">
        {{ current.getDate() }}
      </div>
    </ng-template>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
      .border {
        border: 1px solid #1890ff;
        border-radius: 50%;
      }
    `
  ]
})
export class NzDemoDatePickerDateRenderComponent {}


~

使用 nzFormat 属性,可以自定义日期显示格式。

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-date-picker-format',
  template: `
    <nz-date-picker [nzFormat]="dateFormat"></nz-date-picker>
    <br />
    <nz-month-picker [nzFormat]="monthFormat"></nz-month-picker>
    <br />
    <nz-range-picker [nzFormat]="dateFormat"></nz-range-picker>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerFormatComponent {
  dateFormat = 'yyyy/MM/dd';
  monthFormat = 'yyyy/MM';
}

~

增加选择时间功能,当 nzShowTime 为一个对象时,其属性会传递给内建的 TimePicker

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-date-picker-time',
  template: `
    <nz-date-picker
      nzShowTime
      nzFormat="yyyy-MM-dd HH:mm:ss"
      nzPlaceHolder="Select Time"
      (ngModelChange)="onChange($event)"
      (nzOnOk)="onOk($event)"
    ></nz-date-picker>
    <br />
    <nz-range-picker
      [nzShowTime]="{ nzFormat: 'HH:mm' }"
      nzFormat="yyyy-MM-dd HH:mm"
      [nzPlaceHolder]="['Start Time', 'End Time']"
      (ngModelChange)="onChange($event)"
      (nzOnOk)="onOk($event)"
    ></nz-range-picker>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerTimeComponent {
  onChange(result: Date): void {
    console.log('Selected Time: ', result);
  }

  onOk(result: Date): void {
    console.log('onOk', result);
  }
}



~

可用 nzDisabledDatenzDisabledTime 分别禁止选择部分日期和时间。

expand codeexpand code
import { Component } from '@angular/core';
import differenceInCalendarDays from 'date-fns/difference_in_calendar_days';
import setHours from 'date-fns/set_hours';

@Component({
  selector: 'nz-demo-date-picker-disabled-date',
  template: `
    <nz-date-picker
      nzFormat="yyyy-MM-dd HH:mm:ss"
      [nzDisabledDate]="disabledDate"
      [nzDisabledTime]="disabledDateTime"
      [nzShowTime]="{ nzDefaultOpenValue: timeDefaultValue }"
    >
    </nz-date-picker>
    <br />
    <nz-month-picker [nzDisabledDate]="disabledDate" nzPlaceHolder="Select month"></nz-month-picker>
    <br />
    <nz-year-picker [nzDisabledDate]="disabledDate"></nz-year-picker>
    <br />
    <nz-range-picker
      [nzDisabledDate]="disabledDate"
      [nzDisabledTime]="disabledRangeTime"
      [nzShowTime]="{ nzHideDisabledOptions: true, nzDefaultOpenValue: timeDefaultValue }"
      nzFormat="yyyy-MM-dd HH:mm:ss"
    ></nz-range-picker>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-year-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerDisabledDateComponent {
  today = new Date();
  timeDefaultValue = setHours(new Date(), 0);

  range(start: number, end: number): number[] {
    const result: number[] = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }

  disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, this.today) > 0;
  };

  disabledDateTime = (): object => {
    return {
      nzDisabledHours: () => this.range(0, 24).splice(4, 20),
      nzDisabledMinutes: () => this.range(30, 60),
      nzDisabledSeconds: () => [55, 56]
    };
  };

  disabledRangeTime = (_value: Date[], type: 'start' | 'end'): object => {
    if (type === 'start') {
      return {
        nzDisabledHours: () => this.range(0, 60).splice(4, 20),
        nzDisabledMinutes: () => this.range(30, 60),
        nzDisabledSeconds: () => [55, 56]
      };
    }
    return {
      nzDisabledHours: () => this.range(0, 60).splice(20, 4),
      nzDisabledMinutes: () => this.range(0, 31),
      nzDisabledSeconds: () => [55, 56]
    };
  };
}
~
~

RangePicker 可以设置常用的 预设范围 提高用户体验。

expand codeexpand code
import { Component } from '@angular/core';
import endOfMonth from 'date-fns/end_of_month';

@Component({
  selector: 'nz-demo-date-picker-presetted-ranges',
  template: `
    <nz-range-picker [nzRanges]="ranges1" ngModel (ngModelChange)="onChange($event)"></nz-range-picker>
    <br />
    <nz-range-picker
      [nzRanges]="ranges1"
      nzShowTime
      nzFormat="yyyy/MM/dd HH:mm:ss"
      ngModel
      (ngModelChange)="onChange($event)"
    ></nz-range-picker>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerPresettedRangesComponent {
  ranges1 = { Today: [new Date(), new Date()], 'This Month': [new Date(), endOfMonth(new Date())] };
  ranges2 = { Today: [new Date(), new Date()], 'This Month': [new Date(), endOfMonth(new Date())] };

  onChange(result: Date[]): void {
    console.log('From: ', result[0], ', to: ', result[1]);
  }
}

通过组合 nzModenzOnPanelChange 控制要展示的面板。

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-date-picker-mode',
  template: `
    <nz-date-picker
      [nzMode]="dateMode"
      nzShowTime
      (nzOnOpenChange)="handleDateOpenChange($event)"
      (nzOnPanelChange)="handleDatePanelChange($event)"
    >
    </nz-date-picker>
  `,
  styles: [
    `
      nz-date-picker,
      nz-month-picker,
      nz-range-picker,
      nz-week-picker {
        margin: 0 8px 12px 0;
      }
    `
  ]
})
export class NzDemoDatePickerModeComponent {
  dateMode = 'time';

  handleDateOpenChange(open: boolean): void {
    if (open) {
      this.dateMode = 'time';
    }
  }

  handleDatePanelChange(mode: string): void {
    console.log('handleDatePanelChange: ', mode);
  }
}

API#

注意:nz-date-picker 的部分 locale 来自于 Angular 自身的国际化支持,需要在 app.module.ts 文件中 引入相应的 Angular 语言包。 例如:

import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh';
registerLocaleData(zh);

日期类组件包括以下四种形式。

  • nz-date-picker
  • nz-month-picker
  • nz-range-picker
  • nz-week-picker

注意: 所有输入输出日期对象均为 Date,你可以通过 date-fns 工具库获得你需要的数据。

共同的 API#

以下 API 为 nz-date-picker、nz-month-picker、nz-range-picker, nz-week-picker 共享的 API。

参数说明类型默认值
[nzAllowClear]是否显示清除按钮booleantrue
[nzAutoFocus]自动获取焦点booleanfalse
[nzClassName]选择器 classNamestring''
[nzDateRender]自定义日期单元格的内容(month-picker/year-picker不支持)TemplateRef<Date> | string | ((d: Date) => TemplateRef<Date> | string)-
[nzDisabled]禁用booleanfalse
[nzDisabledDate]不可选择的日期(current: Date) => boolean-
[nzLocale]国际化配置object默认配置
[nzOpen]控制弹层是否展开boolean-
[nzPopupStyle]额外的弹出日历样式object{}
[nzDropdownClassName]额外的弹出日历 classNamestring-
[nzSize]输入框大小,large 高度为 40px,small 为 24px,默认是 32px'large' | 'small'-
[nzStyle]自定义输入框样式object{}
(nzOnOpenChange)弹出日历和关闭日历的回调EventEmitter<boolean>-

nz-date-picker#

参数说明类型默认值
[ngModel]日期Date-
[nzDisabledTime]不可选择的时间(current: Date) => { nzDisabledHours, nzDisabledMinutes, nzDisabledSeconds }-
[nzFormat]展示的日期格式,见nzFormat特别说明string"yyyy-MM-dd"
[nzRenderExtraFooter]在面板中添加额外的页脚TemplateRef | string | (() => TemplateRef | string)-
[nzShowTime]增加时间选择功能object | booleanTimePicker Options
[nzShowToday]是否展示“今天”按钮booleantrue
[nzPlaceHolder]输入框提示文字string-
(nzOnOk)点击确定按钮的回调EventEmitter<Date>-
(ngModelChange)时间发生变化的回调EventEmitter<Date>-

nz-year-picker#

参数说明类型默认值
[ngModel]日期Date-
[nzFormat]展示的日期格式,见nzFormat特别说明string"yyyy"
[nzRenderExtraFooter]在面板中添加额外的页脚TemplateRef | string | (() => TemplateRef | string)-
[nzPlaceHolder]输入框提示文字string-
(ngModelChange)时间发生变化的回调EventEmitter<Date>-

nz-month-picker#

参数说明类型默认值
[ngModel]日期Date-
[nzFormat]展示的日期格式,见nzFormat特别说明string"yyyy-MM"
[nzRenderExtraFooter]在面板中添加额外的页脚TemplateRef | string | (() => TemplateRef | string)-
[nzPlaceHolder]输入框提示文字string-
(ngModelChange)时间发生变化的回调EventEmitter<Date>-

nz-week-picker#

参数说明类型默认值
[ngModel]日期Date-
[nzFormat]展示的日期格式,见nzFormat特别说明string"yyyy-ww"
[nzPlaceHolder]输入框提示文字string-
(ngModelChange)时间发生变化的回调EventEmitter<Date>-

nz-range-picker#

参数说明类型默认值
[ngModel]日期Date[]-
[nzDisabledTime]不可选择的时间(current: Date, partial: 'start' | 'end') => { nzDisabledHours, nzDisabledMinutes, nzDisabledSeconds }-
[nzFormat]展示的日期格式,见nzFormat特别说明string"yyyy-MM-dd"
[nzRanges]预设时间范围快捷选择{ [ key: string ]: Date[] } | { [ key: string ]: () => Date[] }-
[nzRenderExtraFooter]在面板中添加额外的页脚TemplateRef | string | (() => TemplateRef | string)-
[nzShowTime]增加时间选择功能object | booleanTimePicker Options
[nzPlaceHolder]输入框提示文字string[]-
(nzOnOk)点击确定按钮的回调EventEmitter<Date[]>-
(ngModelChange)时间发生变化的回调EventEmitter<Date[]>-
(nzOnCalendarChange)待选日期发生变化的回调EventEmitter<Date[]>-

nzShowTime 中当前支持的 nz-time-picker 参数有:nzFormat, nzHourStep, nzMinuteStep, nzSecondStep, nzDisabledHours, nzDisabledMinutes, nzDisabledSeconds, nzHideDisabledOptions, nzDefaultOpenValue, nzAddOn

nzFormat特别说明#

日期格式化目前同时支持两种方式:DatePipe(默认,语法参考) 和 Date-fns语法参考,见如何使用Date-fns进行日期格式化)。