syncfusion-angular-datetimepicker
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Syncfusion Angular DatetimePicker
实现 Syncfusion Angular DatetimePicker
A comprehensive guide for implementing the Syncfusion Essential JS 2 DatetimePicker component in Angular applications. Learn to create date and time selection interfaces, manage calendars and time pickers, handle events, and customize styling.
这是一份在 Angular 应用中实现 Syncfusion Essential JS 2 DatetimePicker 组件的完整指南,你将学习如何创建日期时间选择界面、管理日历与时间选择器、处理事件以及自定义样式。
DatetimePicker Overview
DatetimePicker 概述
The Syncfusion Angular DatetimePicker component is a combined date and time selection widget that provides:
- Integrated Date & Time Selection: Calendar popup for dates + time picker dropdown for time selection
- Flexible Formatting: Custom date formats, time formats, and locale-aware formatting
- Calendar Views: Month (default), Year, and Decade views with smooth navigation
- Time Intervals: Configurable step intervals (15, 30, 60 minutes, etc.) for time selection
- Range Constraints: Min/max dates and min/max time with strict validation
- Comprehensive Event System: change, focus, blur, open, close, created, destroyed, navigated, renderDayCell events
- Masked Input Support: Optional masked input format for guided user entry
- Persistence & RTL: State persistence across reloads and right-to-left language support
- Advanced Features: Strict mode validation, floating labels, keyboard customization, timezone support
- Accessibility: Full WCAG 2.2 compliance, keyboard navigation, WAI-ARIA support
- Theme Support: Material, Bootstrap, Tailwind, Fabric with light/dark variants
- Mobile Optimized: Full screen mode on mobile devices, touch-friendly interface
Package:
@syncfusion/ej2-angular-datetimepickersSyncfusion Angular DatetimePicker 组件是一个组合式日期时间选择组件,具备以下特性:
- 集成日期与时间选择: 选择日期的日历弹窗 + 选择时间的下拉时间选择器
- 灵活的格式化能力: 自定义日期格式、时间格式以及适配地区的本地化格式化
- 多种日历视图: 月视图(默认)、年视图、十年视图,支持流畅导航
- 可配置时间间隔: 时间选择支持自定义步长(15、30、60分钟等)
- 范围约束: 最小/最大日期、最小/最大时间设置,附带严格校验
- 完善的事件系统: 支持 change、focus、blur、open、close、created、destroyed、navigated、renderDayCell 等事件
- 掩码输入支持: 可选的掩码输入格式,引导用户规范输入
- 状态持久化与RTL支持: 页面重载后保留状态,支持从右到左的书写语言
- 高级特性: 严格模式校验、浮动标签、键盘操作自定义、时区支持
- 无障碍适配: 完全符合 WCAG 2.2 标准,支持键盘导航、WAI-ARIA 规范
- 多主题支持: 内置 Material、Bootstrap、Tailwind、Fabric 主题,支持明暗两种模式
- 移动端优化: 移动端支持全屏模式,界面适配触控操作
依赖包:
@syncfusion/ej2-angular-datetimepickersDocumentation Navigation
文档导航
Read the following references based on your specific needs:
你可以根据自身需求阅读对应参考文档:
Getting Started
入门指南
📄 Read: references/getting-started.md
- Package installation via npm and ng add
- NgModule vs Standalone component setup
- CSS theme imports and dependencies
- Basic datetimepicker implementation
- Component initialization and running the application
- Development server setup
📄 阅读: references/getting-started.md
- 通过 npm 和 ng add 命令安装依赖包
- NgModule 与 Standalone 两种组件的配置方式
- CSS 主题导入与依赖管理
- 基础 DateTimePicker 实现
- 组件初始化与应用运行
- 开发服务配置
Basic Implementation
基础实现
📄 Read: references/basic-implementation.md
- Simple datetime picker with ngModel
- Two-way data binding patterns
- Readonly and disabled states
- Basic validation and constraints
- Event handling fundamentals
- ViewChild component access
📄 阅读: references/basic-implementation.md
- 基于 ngModel 的简易日期时间选择器
- 双向数据绑定方案
- 只读与禁用状态设置
- 基础校验与约束配置
- 事件处理基础
- 通过 ViewChild 访问组件实例
Date & Time Configuration
日期与时间配置
📄 Read: references/date-time-configuration.md
- Date format customization (format property)
- Time format configuration (timeFormat property)
- ISO date string handling
- Date range constraints (min/max dates)
- Time range constraints (minTime/maxTime)
- Parsing multiple input formats (inputFormats)
📄 阅读: references/date-time-configuration.md
- 日期格式自定义(format 属性)
- 时间格式配置(timeFormat 属性)
- ISO 日期字符串处理
- 日期范围约束(min/max 日期)
- 时间范围约束(minTime/maxTime)
- 多输入格式解析(inputFormats)
Calendar & Time Views
日历与时间视图
📄 Read: references/calendar-and-time-views.md
- Calendar view modes (month, year, decade)
- Start and depth properties for view control
- Time picker popup configuration
- Time step intervals and granularity
- ScrollTo position for time scrolling
- Today button and clear button behavior
📄 阅读: references/calendar-and-time-views.md
- 日历视图模式(月、年、十年)
- 用于控制视图的 start 和 depth 属性
- 时间选择器弹窗配置
- 时间步长间隔与粒度设置
- 时间滚动的 ScrollTo 位置配置
- 今日按钮与清空按钮行为设置
Events & Callbacks
事件与回调
📄 Read: references/events-and-callbacks.md
- Change event with ChangedEventArgs
- Focus/blur event handling
- Open/close popup events
- Created/destroyed lifecycle events
- Navigate event for calendar navigation
- RenderDayCell for custom day styling
- Cleared event when clear button is used
📄 阅读: references/events-and-callbacks.md
- 携带 ChangedEventArgs 参数的 change 事件
- focus/blur 事件处理
- 弹窗打开/关闭事件
- created/destroyed 生命周期事件
- 日历导航的 navigate 事件
- 用于自定义日期样式的 RenderDayCell 事件
- 清空按钮触发的 cleared 事件
Methods & Imperative Access
方法与命令式访问
📄 Read: references/methods-and-imperative-access.md
- ViewChild access and component references
- currentView() to get active calendar view
- navigateTo() for programmatic navigation
- focusIn/focusOut for focus management
- destroy() for cleanup and resource release
- getPersistData() for state persistence
📄 阅读: references/methods-and-imperative-access.md
- ViewChild 访问与组件引用
- currentView() 获取当前活跃的日历视图
- navigateTo() 实现编程式导航
- focusIn/focusOut 管理焦点状态
- destroy() 清理与释放资源
- getPersistData() 实现状态持久化
Advanced Features
高级特性
📄 Read: references/advanced-features.md
- Masked input mode with mask placeholders
- State persistence across page reloads
- RTL (Right-to-Left) language support
- Floating label types and behavior
- Strict mode validation and error states
- Keyboard shortcuts and key configuration
- Timezone offset handling
- Full screen mode for mobile devices
- Clear button visibility and behavior
📄 阅读: references/advanced-features.md
- 带掩码占位符的掩码输入模式
- 页面重载后的状态持久化
- RTL(从右到左)语言支持
- 浮动标签类型与行为配置
- 严格模式校验与错误状态
- 键盘快捷键与按键配置
- 时区偏移处理
- 移动端全屏模式
- 清空按钮可见性与行为设置
Styling & Customization
样式与自定义
📄 Read: references/styling-and-customization.md
- CSS class customization (cssClass property)
- Theme selection and switching
- Dark mode implementation
- Component width and z-index configuration
- HTML attribute injection (htmlAttributes)
- Calendar mode selection (Gregorian vs Islamic)
- Day header format options
- Disabled dates and styling states
📄 阅读: references/styling-and-customization.md
- CSS 类自定义(cssClass 属性)
- 主题选择与切换
- 深色模式实现
- 组件宽度与 z-index 配置
- HTML 属性注入(htmlAttributes)
- 日历模式选择(公历 vs 伊斯兰历)
- 日期头部格式选项
- 禁用日期与样式状态设置
Accessibility & Globalization
无障碍与全球化
📄 Read: references/accessibility-and-globalization.md
- WCAG 2.2 and Section 508 compliance standards
- WAI-ARIA attributes and roles
- Keyboard navigation (arrows, enter, space, escape)
- Screen reader compatibility and announcements
- Localization and locale property usage
- Day header format variations
- First day of week customization
- Week numbers and week rules
- RTL text direction support
📄 阅读: references/accessibility-and-globalization.md
- WCAG 2.2 与 508 条款合规标准
- WAI-ARIA 属性与角色配置
- 键盘导航(方向键、回车、空格、ESC)
- 屏幕阅读器兼容性与播报支持
- 本地化与 locale 属性使用
- 日期头部格式差异化配置
- 每周第一天自定义
- 周数与周规则配置
- RTL 文本方向支持
API Reference
API 参考
📄 Read: references/api-reference.md
- Complete property reference with types and defaults
- All method signatures with parameters and return types
- All events with event argument types
- Property descriptions and use cases
- Method examples and common patterns
- Type interfaces and enums
- Key configuration for keyboard shortcuts
- Comprehensive property-by-property guide
📄 阅读: references/api-reference.md
- 完整的属性参考,包含类型与默认值
- 所有方法的签名、参数与返回类型
- 所有事件的事件参数类型
- 属性说明与使用场景
- 方法示例与常用模式
- 类型接口与枚举
- 键盘快捷键核心配置
- 逐属性的完整指南
Quick Start Example
快速入门示例
typescript
// app.component.ts
import { Component } from '@angular/core';
import { ChangedEventArgs } from '@syncfusion/ej2-datetimepickers';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Simple datetime value
dateTimeValue: Date = new Date();
// Configuration
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
dateFormat: string = 'dd/MM/yyyy hh:mm a';
timeFormat: string = 'hh:mm a';
// Event handler
onDateTimeChange(args: ChangedEventArgs): void {
console.log('Selected DateTime:', args.value);
console.log('Event Type:', args.type);
}
onPopupOpen(): void {
console.log('Popup opened');
}
onPopupClose(): void {
console.log('Popup closed');
}
}html
<!-- app.component.html -->
<div style="padding: 20px;">
<h2>Select Date & Time</h2>
<ejs-datetimepicker
id="datetimepicker"
[value]="dateTimeValue"
[format]="dateFormat"
[timeFormat]="timeFormat"
[min]="minDate"
[max]="maxDate"
placeholder="Select date and time"
(change)="onDateTimeChange($event)"
(open)="onPopupOpen()"
(close)="onPopupClose()">
</ejs-datetimepicker>
<p *ngIf="dateTimeValue">
Selected: {{ dateTimeValue | date:'medium' }}
</p>
</div>typescript
// app.component.ts
import { Component } from '@angular/core';
import { ChangedEventArgs } from '@syncfusion/ej2-datetimepickers';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// 简易日期时间值
dateTimeValue: Date = new Date();
// 配置项
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
dateFormat: string = 'dd/MM/yyyy hh:mm a';
timeFormat: string = 'hh:mm a';
// 事件处理函数
onDateTimeChange(args: ChangedEventArgs): void {
console.log('选中的日期时间:', args.value);
console.log('事件类型:', args.type);
}
onPopupOpen(): void {
console.log('弹窗已打开');
}
onPopupClose(): void {
console.log('弹窗已关闭');
}
}html
<!-- app.component.html -->
<div style="padding: 20px;">
<h2>选择日期与时间</h2>
<ejs-datetimepicker
id="datetimepicker"
[value]="dateTimeValue"
[format]="dateFormat"
[timeFormat]="timeFormat"
[min]="minDate"
[max]="maxDate"
placeholder="选择日期和时间"
(change)="onDateTimeChange($event)"
(open)="onPopupOpen()"
(close)="onPopupClose()">
</ejs-datetimepicker>
<p *ngIf="dateTimeValue">
选中值: {{ dateTimeValue | date:'medium' }}
</p>
</div>Common Patterns
常用实现模式
Pattern 1: Datetime Range Selection
模式1:日期时间范围选择
Select a start and end datetime for appointments, bookings, or events:
typescript
export class AppComponent {
startDateTime: Date = new Date();
endDateTime: Date = new Date(Date.now() + 3600000); // +1 hour
onStartChange(args: ChangedEventArgs): void {
// Ensure end is after start
if (this.endDateTime <= args.value) {
this.endDateTime = new Date((args.value as Date).getTime() + 3600000);
}
}
}为预约、预订或活动选择开始与结束日期时间:
typescript
export class AppComponent {
startDateTime: Date = new Date();
endDateTime: Date = new Date(Date.now() + 3600000); // 往后加1小时
onStartChange(args: ChangedEventArgs): void {
// 确保结束时间晚于开始时间
if (this.endDateTime <= args.value) {
this.endDateTime = new Date((args.value as Date).getTime() + 3600000);
}
}
}Pattern 2: Business Hours Only
模式2:仅允许选择工作时间
Restrict time selection to business hours (9 AM - 5 PM):
typescript
export class AppComponent {
minTime: Date = new Date(2026, 2, 24, 9, 0); // 9:00 AM
maxTime: Date = new Date(2026, 2, 24, 17, 0); // 5:00 PM
datetimeValue: Date = new Date(2026, 2, 24, 10, 0);
}html
<ejs-datetimepicker
[value]="datetimeValue"
[minTime]="minTime"
[maxTime]="maxTime"
timeFormat="hh:mm a">
</ejs-datetimepicker>限制时间选择范围为工作时间(早9点到晚5点):
typescript
export class AppComponent {
minTime: Date = new Date(2026, 2, 24, 9, 0); // 上午9:00
maxTime: Date = new Date(2026, 2, 24, 17, 0); // 下午5:00
datetimeValue: Date = new Date(2026, 2, 24, 10, 0);
}html
<ejs-datetimepicker
[value]="datetimeValue"
[minTime]="minTime"
[maxTime]="maxTime"
timeFormat="hh:mm a">
</ejs-datetimepicker>Pattern 3: Masked Input for Guided Entry
模式3:掩码输入引导用户填写
Use masked input to guide users through the datetime format:
typescript
export class AppComponent {
datetimeValue: Date;
maskPlaceholder = {
day: 'dd',
month: 'mm',
year: 'yyyy',
hour: 'hh',
minute: 'mm',
second: 'ss'
};
}html
<ejs-datetimepicker
[value]="datetimeValue"
[enableMask]="true"
[maskPlaceholder]="maskPlaceholder"
format="dd/MM/yyyy hh:mm:ss">
</ejs-datetimepicker>使用掩码输入引导用户按指定格式填写日期时间:
typescript
export class AppComponent {
datetimeValue: Date;
maskPlaceholder = {
day: 'dd',
month: 'mm',
year: 'yyyy',
hour: 'hh',
minute: 'mm',
second: 'ss'
};
}html
<ejs-datetimepicker
[value]="datetimeValue"
[enableMask]="true"
[maskPlaceholder]="maskPlaceholder"
format="dd/MM/yyyy hh:mm:ss">
</ejs-datetimepicker>Pattern 4: Reactive Forms Integration
模式4:响应式表单集成
Integrate datetimepicker with Angular Reactive Forms:
typescript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class AppComponent {
appointmentForm: FormGroup;
constructor(private fb: FormBuilder) {
this.appointmentForm = this.fb.group({
appointmentDateTime: [
new Date(),
[Validators.required]
]
});
}
submitForm(): void {
if (this.appointmentForm.valid) {
console.log(this.appointmentForm.value);
}
}
}html
<form [formGroup]="appointmentForm">
<ejs-datetimepicker
formControlName="appointmentDateTime"
format="dd/MM/yyyy hh:mm a">
</ejs-datetimepicker>
<button (click)="submitForm()" [disabled]="!appointmentForm.valid">
Submit
</button>
</form>将 DateTimePicker 与 Angular 响应式表单集成:
typescript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class AppComponent {
appointmentForm: FormGroup;
constructor(private fb: FormBuilder) {
this.appointmentForm = this.fb.group({
appointmentDateTime: [
new Date(),
[Validators.required]
]
});
}
submitForm(): void {
if (this.appointmentForm.valid) {
console.log(this.appointmentForm.value);
}
}
}html
<form [formGroup]="appointmentForm">
<ejs-datetimepicker
formControlName="appointmentDateTime"
format="dd/MM/yyyy hh:mm a">
</ejs-datetimepicker>
<button (click)="submitForm()" [disabled]="!appointmentForm.valid">
提交
</button>
</form>Pattern 5: Disabled Dates
模式5:禁用指定日期
Disable weekends and specific dates:
typescript
export class AppComponent {
datetimeValue: Date;
onRenderDayCell(args: RenderDayCellEventArgs): void {
// Disable weekends (0 = Sunday, 6 = Saturday)
if ((args.date as Date).getDay() === 0 || (args.date as Date).getDay() === 6) {
args.isDisabled = true;
}
// Disable specific dates
const disabledDates = [5, 15, 25]; // 5th, 15th, 25th of each month
if (disabledDates.includes((args.date as Date).getDate())) {
args.isDisabled = true;
}
}
}html
<ejs-datetimepicker
[value]="datetimeValue"
(renderDayCell)="onRenderDayCell($event)">
</ejs-datetimepicker>禁用周末与特定日期:
typescript
export class AppComponent {
datetimeValue: Date;
onRenderDayCell(args: RenderDayCellEventArgs): void {
// 禁用周末(0 = 周日, 6 = 周六)
if ((args.date as Date).getDay() === 0 || (args.date as Date).getDay() === 6) {
args.isDisabled = true;
}
// 禁用特定日期
const disabledDates = [5, 15, 25]; // 每月的5号、15号、25号
if (disabledDates.includes((args.date as Date).getDate())) {
args.isDisabled = true;
}
}
}html
<ejs-datetimepicker
[value]="datetimeValue"
(renderDayCell)="onRenderDayCell($event)">
</ejs-datetimepicker>Key Properties Reference
核心属性参考
| Property | Type | Purpose |
|---|---|---|
| Date | Selected datetime value for two-way binding |
| string | Date display format (e.g., 'dd/MM/yyyy hh:mm a') |
| string | Time display format in popup (e.g., 'hh:mm a') |
| Date | Minimum selectable date |
| Date | Maximum selectable date |
| Date | Minimum selectable time |
| Date | Maximum selectable time |
| number | Time interval in minutes (15, 30, 60) |
| boolean | Enable/disable the component |
| boolean | Make input readonly (select from popup only) |
| string | Placeholder text in input |
| boolean | Enable masked input mode |
| boolean | Enforce valid values only |
| boolean | Right-to-left language support |
| boolean | Persist value across page reloads |
| CalendarView | Initial calendar view (Month/Year/Decade) |
| CalendarView | Maximum calendar view level |
| string | Locale for formatting (e.g., 'en-US', 'de-DE') |
| 属性 | 类型 | 用途 |
|---|---|---|
| Date | 用于双向绑定的选中日期时间值 |
| string | 日期展示格式(如 'dd/MM/yyyy hh:mm a') |
| string | 弹窗中的时间展示格式(如 'hh:mm a') |
| Date | 最小可选择日期 |
| Date | 最大可选择日期 |
| Date | 最小可选择时间 |
| Date | 最大可选择时间 |
| number | 时间间隔(单位:分钟,可选15、30、60) |
| boolean | 启用/禁用组件 |
| boolean | 将输入框设为只读(仅可通过弹窗选择) |
| string | 输入框占位文本 |
| boolean | 启用掩码输入模式 |
| boolean | 强制仅允许输入有效值 |
| boolean | 支持从右到左的书写语言 |
| boolean | 页面重载后保留组件值 |
| CalendarView | 初始日历视图(月/年/十年) |
| CalendarView | 最大可切换的日历视图层级 |
| string | 格式化使用的地区编码(如 'en-US', 'de-DE') |
Common Use Cases
常见使用场景
Appointment Booking System
预约预订系统
- Use date range selection with business hours time constraints
- Display available time slots based on min/max time
- Handle form validation with required validators
- Show selected datetime confirmation
- 搭配工作时间约束使用日期范围选择
- 根据最小/最大时间展示可预约时段
- 搭配必填校验器实现表单校验
- 展示选中的日期时间确认信息
Event Scheduling
活动排期
- Select start and end datetimes for events
- Disable weekend dates with renderDayCell
- Use step intervals for common durations (30, 60 min)
- Format output for API submission
- 为活动选择开始与结束日期时间
- 通过 renderDayCell 禁用周末日期
- 使用时间步长设置常见活动时长(30、60分钟)
- 格式化输出内容用于API提交
Shift Management
班次管理
- Select shift start and end times
- Apply shift time constraints (min/max time)
- Handle date transitions (shifts spanning midnight)
- Support multiple timezone offsets
- 选择班次的开始与结束时间
- 应用班次时间约束(最小/最大时间)
- 处理跨午夜的班次日期切换
- 支持多时区偏移
Billing & Invoicing
账单与发票系统
- Select invoice date and time
- Restrict to past dates only
- Display in user's locale format
- Export with ISO format
- 选择发票日期与时间
- 仅允许选择过去的日期
- 按用户所在地区格式展示
- 导出为ISO格式
Next Steps
后续步骤
- Start with Getting Started → Install and configure the component
- Build Basic Implementation → Create simple datetime pickers
- Add Event Handling → Respond to user interactions
- Implement Advanced Features → Add masked input, persistence, RTL
- Customize Appearance → Apply themes and custom styles
- Ensure Accessibility → Support keyboard and screen readers
- Reference API → Consult complete API documentation as needed
Ready to get started? Begin with references/getting-started.md for installation and setup instructions.
- 从入门指南开始 → 安装并配置组件
- 实现基础功能 → 创建简单的日期时间选择器
- 添加事件处理 → 响应用户交互
- 集成高级特性 → 添加掩码输入、状态持久化、RTL支持
- 自定义外观 → 应用主题与自定义样式
- 适配无障碍功能 → 支持键盘操作与屏幕阅读器
- 查阅API文档 → 按需参考完整的API文档
准备好开始了吗? 阅读references/getting-started.md获取安装与配置说明。