Skip to main content

ion-datetime

shadow

日期时间提供了一个日历界面和时间滚轮,使用户可以轻松选择日期和时间。日期时间类似于 datetime-local 的原生 input 元素,但 Ionic Framework 的日期时间组件使显示首选格式的日期和时间以及管理日期时间值变得容易。

🌐 Datetimes present a calendar interface and time wheel, making it easy for users to select dates and times. Datetimes are similar to the native input elements of datetime-local, however, Ionic Framework's Datetime component makes it easy to display the date and time in the preferred format, and manage the datetime values.

概述

🌐 Overview

从历史上看,在 JavaScript 中处理日期时间值,甚至在 HTML 输入中处理,一直都是一个挑战。具体来说,JavaScript 的 Date 对象在正确解析日期时间字符串或格式化日期时间值方面臭名昭著地困难。更糟的是,不同浏览器和 JavaScript 版本对各种日期时间字符串的解析方式不同,尤其是根据地区的不同。

🌐 Historically, handling datetime values within JavaScript, or even within HTML inputs, has always been a challenge. Specifically, JavaScript's Date object is notoriously difficult to correctly parse apart datetime strings or to format datetime values. Even worse is how different browsers and JavaScript versions parse various datetime strings differently, especially per locale.

幸运的是,Ionic 框架的日期时间输入设计得很好,使开发者可以避免常见的陷阱,轻松操作日期时间值,并为用户提供一个简单的日期时间选择器,从而带来出色的用户体验。

🌐 Fortunately, Ionic Framework's datetime input has been designed so developers can avoid the common pitfalls, allowing developers to easily manipulate datetime values and give the user a simple datetime picker for a great user experience.

ISO 8601 日期时间格式:YYYY-MM-DDTHH:mmZ

🌐 ISO 8601 Datetime Format: YYYY-MM-DDTHH:mmZ

Ionic 框架使用 ISO 8601 日期时间格式 作为其值。这个值仅仅是一个字符串,而不是使用 JavaScript 的 Date 对象。使用 ISO 日期时间格式可以轻松地在 JSON 对象和数据库中进行序列化和解析。

🌐 Ionic Framework uses the ISO 8601 datetime format for its value. The value is simply a string, rather than using JavaScript's Date object. Using the ISO datetime format makes it easy to serialize and parse within JSON objects and databases.

以下是一些可以与 ion-datetime 一起使用的 ISO 8601 格式示例:

🌐 Below are some examples of ISO 8601 formats that can be used with ion-datetime:

描述格式日期时间值示例
YYYY1994
年和月YYYY-MM1994-12
完整日期YYYY-MM-DD1994-12-15
日期和时间YYYY-MM-DDTHH:mm1994-12-15T13:47
UTC 时区YYYY-MM-DDTHH:mm:ssZ1994-12-15T13:47:20Z
时区偏移YYYY-MM-DDTHH:mm:ssTZD1994-12-15T13:47:20+05:00
时和分HH:mm13:47

请注意,年份始终为四位数,毫秒(如果有的话)始终为三位数,其他所有都是两位数。因此,表示一月的数字总是有前导零,例如 01。此外,小时始终为24小时制,因此 00 在12小时制中为 12am13 表示 1pm,而 23 表示 11pm

🌐 Note that the year is always four-digits, milliseconds (if it's added) is always three-digits, and all others are always two-digits. So the number representing January always has a leading zero, such as 01. Additionally, the hour is always in the 24-hour format, so 00 is 12am on a 12-hour clock, 13 means 1pm, and 23 means 11pm.

note

虽然秒数、毫秒和时区可以使用 ISO 8601 日期时间格式指定,但 ion-datetime 不提供秒、毫秒和时区的选择界面。任何提供的秒、毫秒或时区值都会被忽略。

基本用法

🌐 Basic Usage

与日期时间按钮一起使用

🌐 Usage with Datetime Button

如果你需要在叠加层中显示日期时间,例如模态框或弹出框,我们建议使用 ion-datetime-button。当空间有限时应使用 ion-datetime-button。该组件显示按钮,显示当前的日期和时间值。当点击按钮时,日期或时间选择器将在叠加层中打开。

🌐 If you need to present a datetime in an overlay such as a modal or a popover, we recommend using ion-datetime-button. ion-datetime-button should be used when space is constrained. This component displays buttons which show the current date and time values. When the buttons are tapped, the date or time pickers open in the overlay.

异步设置值

🌐 Setting Values Asynchronously

如果其 value 在日期时间已经创建后以编程方式更新,日期时间将自动跳转到新的日期。然而,当用户可以与日期时间交互时,建议避免以这种方式更新 value,因为这可能会让当前正在选择日期的人感到困惑。例如,如果日期时间的 value 由异步进程加载,建议在值更新完成之前使用 CSS 隐藏日期时间。

🌐 If its value is updated programmatically after a datetime has already been created, the datetime will automatically jump to the new date. However, it is recommended to avoid updating the value in this way when users are able to interact with the datetime, as this could be disorienting for those currently trying to select a date. For example, if a datetime's value is loaded by an asynchronous process, it is recommended to hide the datetime with CSS until the value has finished updating.

日期限制

🌐 Date Constraints

最大和最小日期

🌐 Max and Min Dates

要自定义最小和最大日期时间值,可以提供 minmax 组件属性,这可能更符合应用的使用场景。按照上表中列出的相同 ISO 8601 格式,每个组件都可以限制用户可以选择的日期。

🌐 To customize the minimum and maximum datetime values, the min and max component properties can be provided which may make more sense for the app's use-case. Following the same IS0 8601 format listed in the table above, each component can restrict which dates can be selected by the user.

以下示例将日期选择限制为仅 2022 年 3 月到 2022 年 5 月。

🌐 The following example restricts date selection to March 2022 through May 2022 only.

选择特定值

🌐 Selecting Specific Values

虽然 minmax 属性允许你将日期选择限制在某个范围内,但 monthValuesdayValuesyearValueshourValuesminuteValues 属性允许你选择用户可以选择的特定日期和时间。

🌐 While the min and max properties allow you to restrict date selection to a certain range, the monthValues, dayValues, yearValues, hourValues, and minuteValues properties allow you choose specific days and times that users can select.

以下示例允许以15分钟为增量选择分钟。它还允许以5天为增量选择日期。

🌐 The following example allows minutes to be selected in increments of 15. It also allows for days to be selected in increments of 5.

高级日期约束

🌐 Advanced Date Constraints

通过 isDateEnabled 属性,开发者可以自定义 ion-datetime,使用 ISO 8601 日期字符串禁用特定的日期、日期范围、周末或任何自定义规则。 isDateEnabled 属性接受一个返回布尔值的函数,用于指示某个日期是否可用。该函数会在渲染的每一天调用,包括上个月、本月和下个月的日期。自定义实现应优化性能,以避免卡顿。

🌐 With the isDateEnabled property, developers can customize the ion-datetime to disable a specific day, range of dates, weekends or any custom rule using an ISO 8601 date string. The isDateEnabled property accepts a function returning a boolean, indicating if a date is enabled. The function is called for each rendered calendar day, for the previous, current and next month. Custom implementations should be optimized for performance to avoid jank.

以下示例展示了如何禁用所有周末日期。对于更高级的日期操作,我们建议使用诸如 date-fns 的日期工具。

🌐 The following example shows how to disable all weekend dates. For more advanced date manipulation, we recommend using a date utility such as date-fns.

本土化

🌐 Localization

Ionic 框架使用 Intl.DatetimeFormat Web API,它允许我们根据用户设备上设置的语言和地区自动本地化月份和星期名称。

🌐 Ionic Framework makes use of the Intl.DatetimeFormat Web API which allows us to automatically localize the month and day names according to the language and region set on the user's device.

自定义区域设置

🌐 Custom Locale

在需要特定区域设置的情况下,你可以使用 locale 属性来设置它。区域设置控制显示的语言以及日期和时间格式。

🌐 For instances where you need a specific locale, you can use the locale property to set it. The locale controls both the language and the date and time formats that are displayed.

以下示例显示如何将区域设置设置为西班牙语(西班牙)。

🌐 The following example shows how to set the locale to Spanish (Spain).

note

时间标签不会自动本地化。有关更多信息,请参见 时间标签

小时周期

🌐 Hour Cycle

ion-datetime 默认将使用由 locale 属性指定的小时周期。例如,如果 locale 设置为 en-US,那么 ion-datetime 将使用 12 小时制周期。

有 4 种主要的小时周期类型:

🌐 There are 4 primary hour cycle types:

小时循环类型描述
'h12'使用 1–12 的小时系统;对应模式中的 'h'。12 小时制,午夜从 12:00 am 开始。
'h23'使用 0–23 的小时系统;对应模式中的 'H'。24 小时制,午夜从 0:00 开始。
'h11'使用 0–11 的小时系统;对应模式中的 'K'。12 小时制,午夜从 0:00 am 开始。
'h24'使用 1–24 的小时系统;对应模式中的 'k'。24 小时制,午夜从 24:00 开始。

可能会有一些情况,你需要对使用哪个小时循环有更多的控制。这时候,hourCycle 属性就可以帮忙。

🌐 There may be scenarios where you need to have more control over which hour cycle is used. This is where the hourCycle property can help.

在以下示例中,我们可以使用 hourCycle 属性强制 ion-datetime 使用 12 小时制,即使本地设置为 en-GB,其默认使用 24 小时制:

🌐 In the following example, we can use the hourCycle property to force ion-datetime to use the 12 hour cycle even though the locale is en-GB, which uses a 24 hour cycle by default:

一周的第一天

🌐 First Day of the Week

对于 ion-datetime,默认的一周的第一天是星期日。截至 2022 年,还没有浏览器 API 可以让 Ionic 根据设备的区域设置自动确定一周的第一天,不过这方面正在进行相关工作(参见:TC39 GitHub)。

🌐 For ion-datetime, the default first day of the week is Sunday. As of 2022, there is no browser API that lets Ionic automatically determine the first day of the week based on a device's locale, though there is on-going work regarding this (see: TC39 GitHub).

时间标签

🌐 Time Label

时间标签不会自动本地化。幸运的是,Ionic 使得通过 time-label 插槽提供自定义本地化变得很容易。

🌐 The time label is not automatically localized. Fortunately, Ionic makes it easy to provide custom localizations with the time-label slot.

区域设置扩展标签

🌐 Locale Extension Tags

ion-datetime 也支持作为 Intl.Locale API 一部分的 区域设置扩展标签。这些标签允许你在区域设置字符串本身中编码有关区域设置信息。如果开发者在应用中使用 Intl.Locale API,他们可能更倾向于使用扩展标签的方法。

例如,如果你想在 en-GB 语言环境中使用 12 小时制周期,你可以提供扩展标签,而不是同时使用 localehourCycle 属性:

🌐 For example, if you wanted to use a 12 hour cycle with the en-GB locale, you could provide extension tags instead of using both the locale and hourCycle properties:

note

在将 Intl.Locale 用于你的应用之前,请务必查看 浏览器兼容性图表

渲染

🌐 Presentation

默认情况下,ion-datetime 允许用户选择日期和时间。此外,用户还可以选择具体的月份、年份、小时和分钟。

🌐 By default, ion-datetime allows users to select both date and time. In addition, users have access to selecting the specific month, year, hour, and minute.

某些使用场景可能只需要选择日期或只需要选择时间。presentation 属性允许你指定要显示的选择器以及显示的顺序。例如,设置 date-time 将使日历选择器出现在时间选择器之前。设置 time-date 将使日历选择器出现在时间选择器之后。

🌐 Some use cases may call for only date selection or only time selection. The presentation property allows you to specify which pickers to show and the order to show them in. For example, setting date-time will have the calendar picker appear before the time picker. Setting time-date will have the calendar picker appear after the time picker.

月份和年份选择

🌐 Month and Year Selection

通过将 month-yearmonthyear 传递给 presentation 属性,可以选择月份和年份。

🌐 Month and year selection is available by passing month-year, month, or year to the presentation property.

此示例显示了带有 month-year 配置的日期时间。

🌐 This example shows a datetime with the month-year configuration.

时间选择

🌐 Time Selection

可以通过将 date-timetime-datetime 传递给 presentation 属性来选择时间。

🌐 Time selection is available by passing date-time, time-date, or time to the presentation property.

此示例显示了使用 time 配置的日期时间。

🌐 This example shows a datetime with the time configuration.

日期选择

🌐 Date Selection

可以通过将 date-timetime-datedate 传递给 presentation 属性来选择日期。

🌐 Date selection is available by passing date-time, time-date, or date to the presentation property.

此示例显示了使用 date 配置的日期时间。

🌐 This example shows a datetime with the date configuration.

轮式拾取器

🌐 Wheel Style Pickers

默认情况下,当使用 presentation 时,Ionic 会倾向于显示网格样式布局。但是,可以使用 preferWheel 属性显示滚轮样式。当 preferWheeltrue 时,Ionic 会在可能的情况下倾向于显示滚轮样式布局。

🌐 By default, Ionic will prefer to show a grid style layout when using presentation. However, it is possible to show a wheel style using the preferWheel property. When preferWheel is true, Ionic will prefer to show the wheel style layout when possible.

某些 presentation 选项具有开发者可以通过 preferWheel 属性选择的网格和滚轮样式。其他 presentation 值仅具有滚轮样式,永远不会显示网格样式。下表显示了哪些 presentation 值具有网格或滚轮样式。

🌐 Certain presentation options have both grid and wheel styles that developers can choose from with the preferWheel property. Other presentation values only have a wheel style and will never show a grid style. The table below shows which presentation values have grid or wheel styles.

presentation有网格样式吗?有轮子样式吗?
date
date-time
month
month-year
time
time-date
year

下面的示例显示了带有 presentation="date-time" 的滚轮选择器。

🌐 The example below shows the wheel picker with presentation="date-time".

显示相邻日期

🌐 Show Adjacent Days

如果 showAdjacentDays 属性被设置为 true,日历视图中将显示前一个和下一个月份的日期,以填充月初或月末的空白。当用户点击一个可用的相邻日期时,日历将平滑地动画切换到该月份的视图。

🌐 If the showAdjacentDays property is set to true, days from the previous and next month will be displayed in the calendar view to fill any empty spaces at the beginning or end of the month. When a user clicks on an enabled adjacent day, the calendar will smoothly animate to show that month's view.

当启用 showAdjacentDays 时,日历视图总是显示 6 行,因此会根据需要显示上个月或下个月的日期以填满网格。例如,即使某个月从一周的第一天开始并在第五行内结束,下个月的日子也会出现在末尾以完成第六行。

🌐 The calendar view always displays 6 rows when showAdjacentDays is enabled, so days from the previous or next month will be shown as needed to fill the grid. For example, even if a month starts on the first day of the week and ends within the fifth row, days from the next month will appear at the end to complete the sixth row.

note

此属性仅在使用 presentation="date"preferWheel="false" 时受支持。

多个日期选择

🌐 Multiple Date Selection

如果将 multiple 属性设置为 true,可以从日历选择器中选择多个日期。点击已选择的日期将取消选择它。

🌐 If the multiple property is set to true, multiple dates can be selected from the calendar picker. Clicking a selected date will deselect it.

note

此属性仅在使用 presentation="date"preferWheel="false" 时受支持。

标题

🌐 Titles

默认情况下,ion-datetime 不显示与组件关联的任何标题或标题。开发者可以使用 showDefaultTitle 属性显示默认的标题/标题配置。他们还可以使用 title 插槽来自定义在标题中渲染的内容。

🌐 By default, ion-datetime does not show any header or title associated with the component. Developers can use the showDefaultTitle property to show the default title/header configuration. They can also use the title slot to customize what is rendered in the header.

显示默认标题

🌐 Showing the Default Title

自定义标题

🌐 Customizing the Title

格式选项

🌐 Format Options

你可以通过提供 formatOptions 来自定义 Datetime 组件中标题文本的日期格式和时间按钮的时间格式。formatOptions 属性中的 datetime 应分别是 Intl.DateTimeFormatOptions 对象。如果未提供 formatOptions,将使用日期和时间的默认格式。

🌐 You can customize the format of the date in the header text and the time in the time button of a Datetime component by providing formatOptions. The date and time in the formatOptions property should each be an Intl.DateTimeFormatOptions object. If formatOptions is not provided, default formats will be used for dates and times.

Datetime 不操作或设置 时区。如果提供了 timeZonetimeZoneName,它们将被忽略,并且时区将设置为 UTC。这确保显示的值与所选值匹配,而不是转换为用户当前的时区。

🌐 Datetime does not manipulate or set the time zone. If timeZone or timeZoneName are provided, they will be ignored, and the time zone will be set to UTC. This ensures that the displayed value matches the selected value, rather than being converted to the user's current time zone.

请小心你提供的选项,因为它们可能与所选的演示方式不匹配。例如,为 month 的演示提供 minute: 'numeric' 可能会导致意外的行为,显示一个月份,而原本可能只预期时间。

🌐 Be careful with the options you provide, as they may not match the selected presentation. For example, providing minute: 'numeric' for a presentation of month may lead to unexpected behavior, displaying a month where only a time might be expected.

按钮

🌐 Buttons

默认情况下,每当选择新日期时,ionChange 会随新的日期时间值一起触发。要在触发 ionChange 之前要求用户确认,你可以将 showDefaultButtons 属性设置为 true,或者使用 buttons 插槽传入自定义确认按钮。在传入自定义按钮时,确认按钮必须调用 ion-datetime 上的 confirm 方法,才能触发 ionChange

🌐 By default, ionChange is emitted with the new datetime value whenever a new date is selected. To require user confirmation before emitting ionChange, you can either set the showDefaultButtons property to true or use the buttons slot to pass in a custom confirmation button. When passing in custom buttons, the confirm button must call the confirm method on ion-datetime for ionChange to be emitted.

显示确认按钮

🌐 Showing Confirmation Buttons

默认的“完成”和“取消”按钮已经预先配置为分别调用 confirmcancel 方法。

🌐 The default Done and Cancel buttons are already preconfigured to call the confirm and cancel methods, respectively.

自定义按钮文本

🌐 Customizing Button Texts

对于简单的使用场景,开发者可以通过 doneTextcancelText 属性为确认和取消按钮提供自定义文本。我们建议仅在你只需要更改按钮文本而不需要任何自定义行为时这样做。

🌐 For simple use cases, developers can provide custom button text to the confirmation and cancel values through the doneText and cancelText properties. We recommend doing this when you only need to change the button text and do not need any custom behavior.

自定义按钮元素

🌐 Customizing Button Elements

开发者可以提供自己的按钮来实现高级自定义行为。

🌐 Developers can provide their own buttons for advanced custom behavior.

ion-datetimeconfirmcancelreset 方法,开发者可以在点击自定义按钮时调用。reset 方法还允许开发者提供一个日期来重置日期时间。

高亮特定日期

🌐 Highlighting Specific Dates

使用 highlightedDates 属性,开发者可以为特定日期设置自定义的文本或背景颜色。该属性可以定义为日期及其颜色的数组,或者一个回调函数,该函数接收一个 ISO 字符串并返回要使用的颜色。

🌐 Using the highlightedDates property, developers can style particular dates with custom text or background colors. This property can be defined as either an array of dates and their colors, or a callback that receives an ISO string and returns the colors to use.

在指定颜色时,可以使用任何有效的 CSS 颜色格式。这包括十六进制代码、rgba颜色变量 等。

🌐 When specifying colors, any valid CSS color format can be used. This includes hex codes, rgba, color variables, etc.

为了保持一致的用户体验,所选日期的样式将始终覆盖自定义高亮。

🌐 To maintain a consistent user experience, the style of selected date(s) will always override custom highlights.

note

此属性仅在 preferWheel="false" 时受支持,并且使用 presentation"date""date-time""time-date"

使用数组

🌐 Using Array

当高亮应用于固定日期(例如截止日期)时,数组会更好。

🌐 An array is better when the highlights apply to fixed dates, such as due dates.

使用回调

🌐 Using Callback

当高亮的日期重复出现时(例如生日或重复会议),回调效果更好。

🌐 A callback is better when the highlighted dates are recurring, such as birthdays or recurring meetings.

样式

🌐 Styling

全局主题

🌐 Global Theming

Ionic 强大的主题系统可以用来轻松更改整个应用以匹配某个特定主题。在这个例子中,我们使用了 Color CreatorStepped Color Generator 来创建一个玫瑰色调色板,我们可以将其用于 ion-datetime

🌐 Ionic's powerful theming system can be used to easily change your entire app to match a certain theme. In this example, we used the Color Creator and the Stepped Color Generator to create a rose color palette that we can use for ion-datetime.

这种方法的好处在于,每个组件,而不仅仅是 ion-datetime,都可以自动利用这一主题。

🌐 The benefit of this approach is that every component, not just ion-datetime, can automatically take advantage of this theme.

日期时间头

🌐 Datetime Header

datetime 头管理 title 插槽和所选日期的内容。

🌐 The datetime header manages the content for the title slot and the selected date.

note

如果 preferWheel 设置为 true,所选日期将无法渲染。

日历标题

🌐 Calender Header

日历标题管理日期导航控件(月份/年份选择器和上一个/下一个按钮)以及在使用网格样式布局时的星期几。

🌐 The calendar header manages the date navigation controls (month/year picker and prev/next buttons) and the days of the week when using a grid style layout.

可以使用 CSS 阴影部分来设置标题样式。

🌐 The header can be styled using CSS shadow parts.

日历日

🌐 Calendar Days

网格样式 ion-datetime 中的日历天可以使用 CSS 阴影部分进行样式设置。

🌐 The calendar days in a grid-style ion-datetime can be styled using CSS shadow parts.

note

下面的示例会选择两天前的日期,除非该日期在上个月,那么它会选择未来两天的日期。这是出于演示目的,旨在展示如何对所有日期、当前日期和选定日期应用自定义样式。

轮式拾取器

🌐 Wheel Pickers

ion-datetime 中使用的滚轮可以通过阴影部分和 CSS 变量的组合进行样式设置。这适用于滚轮样式日期时间中的列,以及网格样式日期时间中的月份/年份选择器。

🌐 The wheels used in ion-datetime can be styled through a combination of shadow parts and CSS variables. This applies to both the columns in wheel-style datetimes, and the month/year picker in grid-style datetimes.

时区

🌐 Time Zones

Ionic 的 ion-datetime 遵循 datetime-local 的行为,不会在日期时间控件中操作或设置时区。换句话说,时间值 "07:00" 不会根据不同的时区进行调整。

🌐 Ionic's ion-datetime follows the datetime-local behavior of not manipulating or setting the time zone inside of a datetime control. In other words, a time value of "07:00" will not be adjusted according to different time zones.

我们建议使用像 date-fns-tz 这样的库将日期时间值转换为所需的时区。

🌐 We recommend using a library such as date-fns-tz to convert a datetime value to the desired time zone.

以下是格式化 ISO-8601 字符串以在用户设备上设置的时区中显示的示例:

🌐 Below is an example of formatting an ISO-8601 string to display in the time zone set on a user's device:

import { format, utcToZonedTime } from 'date-fns-tz';

// Get the time zone set on the user's device
const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

// Create a date object from a UTC date string
const date = new Date('2014-10-25T10:46:20Z');

// Use date-fns-tz to convert from UTC to a zoned time
const zonedTime = utcToZonedTime(date, userTimeZone);

// Create a formatted string from the zoned time
format(zonedTime, 'yyyy-MM-dd HH:mm:ssXXX', { timeZone: userTimeZone });

解析日期值

🌐 Parsing Date Values

ionChange 事件将在事件负载中以 ISO-8601 字符串的形式发出日期值。开发者有责任根据其应用需求对其进行格式化。我们建议使用 date-fns 来格式化日期值。

🌐 The ionChange event will emit the date value as an ISO-8601 string in the event payload. It is the developer's responsibility to format it based on their application needs. We recommend using date-fns to format the date value.

下面是格式化 ISO-8601 字符串以显示月份、日期和年份的示例:

🌐 Below is an example of formatting an ISO-8601 string to display the month, date and year:

import { format, parseISO } from 'date-fns';

/**
* This is provided in the event
* payload from the `ionChange` event.
*
* The value is an ISO-8601 date string.
*/
const dateFromIonDatetime = '2021-06-04T14:23:00-04:00';
const formattedString = format(parseISO(dateFromIonDatetime), 'MMM d, yyyy');

console.log(formattedString); // Jun 4, 2021

请参阅 https://date-fns.org/docs/format 获取所有有效格式标记的列表。

🌐 See https://date-fns.org/docs/format for a list of all the valid format tokens.

高级日期时间验证和操作

🌐 Advanced Datetime Validation and Manipulation

日期时间选择器提供了选择精确格式的简便方式,并将日期时间值以字符串形式保持,使用标准化的ISO 8601日期时间格式。然而,需要注意的是,ion-datetime 并不试图解决在验证和操作日期时间值时的所有情况。如果需要从特定格式解析日期时间值,或进行操作(例如向日期添加5天,减去30分钟等),甚至将数据格式化为特定的本地化格式,那么我们强烈建议使用 date-fns 在 JavaScript 中处理日期。

🌐 The datetime picker provides the simplicity of selecting an exact format, and persists the datetime values as a string using the standardized ISO 8601 datetime format. However, it's important to note that ion-datetime does not attempt to solve all situations when validating and manipulating datetime values. If datetime values need to be parsed from a certain format, or manipulated (such as adding 5 days to a date, subtracting 30 minutes, etc.), or even formatting data to a specific locale, then we highly recommend using date-fns to work with dates in JavaScript.

无障碍

🌐 Accessibility

键盘交互

🌐 Keyboard Interactions

ion-datetime 对组件内可获取焦点的元素之间的导航提供完整的键盘支持。下表详细说明了每个键的功能:

描述
Tab将焦点移到下一个可聚焦的元素。
Shift + Tab将焦点移到上一个可聚焦的元素。
SpaceEnter点击可聚焦的元素。

日期网格

🌐 Date Grid

描述
ArrowUp将焦点移动到上一周的同一天。
ArrowDown将焦点移动到下一周的同一天。
ArrowRight将焦点移动到下一天。
ArrowLeft将焦点移动到前一天。
Home将焦点移动到本周的第一天。
End将焦点移动到本周的最后一天。
PageUp将日期网格更改为上个月。
PageDown将日期网格更改为下个月。
Shift + PageUp将日期网格更改为上一年。
Shift + PageDown将日期网格更改为下一年。

时间、月份和年份轮

🌐 Time, Month, and Year Wheels

Datetime 中的滚轮选择器内部使用 Picker。有关滚轮选择器的无障碍功能的更多信息,请参阅 Picker 无障碍

🌐 The wheel picker in Datetime uses Picker internally. See Picker Accessibility for more information on accessibility features with the wheel picker.

接口

🌐 Interfaces

DatetimeChangeEventDetail

interface DatetimeChangeEventDetail {
value?: string | null;
}

DatetimeCustomEvent

虽然不是必需的,但可以使用此接口替代 CustomEvent 接口,以便对从此组件发出的 Ionic 事件进行更强类型的处理。

🌐 While not required, this interface can be used in place of the CustomEvent interface for stronger typing with Ionic events emitted from this component.

interface DatetimeCustomEvent extends CustomEvent {
detail: DatetimeChangeEventDetail;
target: HTMLIonDatetimeElement;
}

属性

🌐 Properties

cancelText

DescriptionThe text to display on the picker's cancel button.
Attributecancel-text
Typestring
Default'Cancel'

clearText

DescriptionThe text to display on the picker's "Clear" button.
Attributeclear-text
Typestring
Default'Clear'

color

DescriptionThe color to use from your application's color palette. Default options are: "primary", "secondary", "tertiary", "success", "warning", "danger", "light", "medium", and "dark". For more information on colors, see theming.
Attributecolor
Type"danger" | "dark" | "light" | "medium" | "primary" | "secondary" | "success" | "tertiary" | "warning" | string | undefined
Default'primary'

dayValues

DescriptionValues used to create the list of selectable days. By default every day is shown for the given month. However, to control exactly which days of the month to display, the dayValues input can take a number, an array of numbers, or a string of comma separated numbers. Note that even if the array days have an invalid number for the selected month, like 31 in February, it will correctly not show days which are not valid for the selected month.
Attributeday-values
Typenumber | number[] | string | undefined
Defaultundefined

disabled

DescriptionIf true, the user cannot interact with the datetime.
Attributedisabled
Typeboolean
Defaultfalse

doneText

DescriptionThe text to display on the picker's "Done" button.
Attributedone-text
Typestring
Default'Done'

firstDayOfWeek

DescriptionThe first day of the week to use for ion-datetime. The default value is 0 and represents Sunday.
Attributefirst-day-of-week
Typenumber
Default0

formatOptions

DescriptionFormatting options for dates and times. Should include a 'date' and/or 'time' object, each of which is of type Intl.DateTimeFormatOptions.
Attributeundefined
Typeundefined | { date: DateTimeFormatOptions; time?: DateTimeFormatOptions | undefined; } | { date?: DateTimeFormatOptions | undefined; time: DateTimeFormatOptions; }
Defaultundefined

highlightedDates

DescriptionUsed to apply custom text and background colors to specific dates.

Can be either an array of objects containing ISO strings and colors, or a callback that receives an ISO string and returns the colors.

Only applies to the date, date-time, and time-date presentations, with preferWheel="false".
Attributeundefined
Type((dateIsoString: string) => DatetimeHighlightStyle | undefined) | DatetimeHighlight[] | undefined
Defaultundefined

hourCycle

DescriptionThe hour cycle of the ion-datetime. If no value is set, this is specified by the current locale.
Attributehour-cycle
Type"h11" | "h12" | "h23" | "h24" | undefined
Defaultundefined

hourValues

DescriptionValues used to create the list of selectable hours. By default the hour values range from 0 to 23 for 24-hour, or 1 to 12 for 12-hour. However, to control exactly which hours to display, the hourValues input can take a number, an array of numbers, or a string of comma separated numbers.
Attributehour-values
Typenumber | number[] | string | undefined
Defaultundefined

isDateEnabled

DescriptionReturns if an individual date (calendar day) is enabled or disabled.

If true, the day will be enabled/interactive. If false, the day will be disabled/non-interactive.

The function accepts an ISO 8601 date string of a given day. By default, all days are enabled. Developers can use this function to write custom logic to disable certain days.

The function is called for each rendered calendar day, for the previous, current and next month. Custom implementations should be optimized for performance to avoid jank.
Attributeundefined
Type((dateIsoString: string) => boolean) | undefined
Defaultundefined

locale

DescriptionThe locale to use for ion-datetime. This impacts month and day name formatting. The "default" value refers to the default locale set by your device.
Attributelocale
Typestring
Default'default'

max

DescriptionThe maximum datetime allowed. Value must be a date string following the ISO 8601 datetime format standard, 1996-12-19. The format does not have to be specific to an exact datetime. For example, the maximum could just be the year, such as 1994. Defaults to the end of this year.
Attributemax
Typestring | undefined
Defaultundefined

min

DescriptionThe minimum datetime allowed. Value must be a date string following the ISO 8601 datetime format standard, such as 1996-12-19. The format does not have to be specific to an exact datetime. For example, the minimum could just be the year, such as 1994. Defaults to the beginning of the year, 100 years ago from today.

This is a virtual property that is set once during initialization and will not update if you change its value after the initial render.
Attributemin
Typestring | undefined
Defaultundefined

minuteValues

DescriptionValues used to create the list of selectable minutes. By default the minutes range from 0 to 59. However, to control exactly which minutes to display, the minuteValues input can take a number, an array of numbers, or a string of comma separated numbers. For example, if the minute selections should only be every 15 minutes, then this input value would be minuteValues="0,15,30,45".
Attributeminute-values
Typenumber | number[] | string | undefined
Defaultundefined

mode

DescriptionThe mode determines which platform styles to use.

This is a virtual property that is set once during initialization and will not update if you change its value after the initial render.
Attributemode
Type"ios" | "md"
Defaultundefined

monthValues

DescriptionValues used to create the list of selectable months. By default the month values range from 1 to 12. However, to control exactly which months to display, the monthValues input can take a number, an array of numbers, or a string of comma separated numbers. For example, if only summer months should be shown, then this input value would be monthValues="6,7,8". Note that month numbers do not have a zero-based index, meaning January's value is 1, and December's is 12.
Attributemonth-values
Typenumber | number[] | string | undefined
Defaultundefined

multiple

DescriptionIf true, multiple dates can be selected at once. Only applies to presentation="date" and preferWheel="false".
Attributemultiple
Typeboolean
Defaultfalse

name

DescriptionThe name of the control, which is submitted with the form data.
Attributename
Typestring
Defaultthis.inputId

preferWheel

DescriptionIf true, a wheel picker will be rendered instead of a calendar grid where possible. If false, a calendar grid will be rendered instead of a wheel picker where possible.

A wheel picker can be rendered instead of a grid when presentation is one of the following values: "date", "date-time", or "time-date".

A wheel picker will always be rendered regardless of the preferWheel value when presentation is one of the following values: "time", "month", "month-year", or "year".
Attributeprefer-wheel
Typeboolean
Defaultfalse

presentation

DescriptionWhich values you want to select. "date" will show a calendar picker to select the month, day, and year. "time" will show a time picker to select the hour, minute, and (optionally) AM/PM. "date-time" will show the date picker first and time picker second. "time-date" will show the time picker first and date picker second.
Attributepresentation
Type"date" | "date-time" | "month" | "month-year" | "time" | "time-date" | "year"
Default'date-time'

readonly

DescriptionIf true, the datetime appears normal but the selected date cannot be changed.
Attributereadonly
Typeboolean
Defaultfalse

showAdjacentDays

DescriptionIf true, the datetime calendar displays a six-week (42-day) layout, including days from the previous and next months to fill the grid. These adjacent days are selectable unless disabled.
Attributeshow-adjacent-days
Typeboolean
Defaultfalse

showClearButton

DescriptionIf true, a "Clear" button will be rendered alongside the default "Cancel" and "OK" buttons at the bottom of the ion-datetime component. Developers can also use the button slot if they want to customize these buttons. If custom buttons are set in the button slot then the default buttons will not be rendered.
Attributeshow-clear-button
Typeboolean
Defaultfalse

showDefaultButtons

DescriptionIf true, the default "Cancel" and "OK" buttons will be rendered at the bottom of the ion-datetime component. Developers can also use the button slot if they want to customize these buttons. If custom buttons are set in the button slot then the default buttons will not be rendered.
Attributeshow-default-buttons
Typeboolean
Defaultfalse

showDefaultTimeLabel

DescriptionIf true, the default "Time" label will be rendered for the time selector of the ion-datetime component. Developers can also use the time-label slot if they want to customize this label. If a custom label is set in the time-label slot then the default label will not be rendered.
Attributeshow-default-time-label
Typeboolean
Defaulttrue

showDefaultTitle

DescriptionIf true, a header will be shown above the calendar picker. This will include both the slotted title, and the selected date.
Attributeshow-default-title
Typeboolean
Defaultfalse

size

DescriptionIf cover, the ion-datetime will expand to cover the full width of its container. If fixed, the ion-datetime will have a fixed width.
Attributesize
Type"cover" | "fixed"
Default'fixed'

titleSelectedDatesFormatter

DescriptionA callback used to format the header text that shows how many dates are selected. Only used if there are 0 or more than 1 selected (i.e. unused for exactly 1). By default, the header text is set to "numberOfDates days".

See https://ionicframework.com/docs/troubleshooting/runtime#accessing-this if you need to access this from within the callback.
Attributeundefined
Type((selectedDates: string[]) => string) | undefined
Defaultundefined

value

DescriptionThe value of the datetime as a valid ISO 8601 datetime string. This should be an array of strings only when multiple="true".
Attributevalue
Typenull | string | string[] | undefined
Defaultundefined

yearValues

DescriptionValues used to create the list of selectable years. By default the year values range between the min and max datetime inputs. However, to control exactly which years to display, the yearValues input can take a number, an array of numbers, or string of comma separated numbers. For example, to show upcoming and recent leap years, then this input's value would be yearValues="2008,2012,2016,2020,2024".
Attributeyear-values
Typenumber | number[] | string | undefined
Defaultundefined

事件

🌐 Events

NameDescriptionBubbles
ionBlurEmitted when the datetime loses focus.true
ionCancelEmitted when the datetime selection was cancelled.true
ionChangeEmitted when the value (selected date) has changed.

This event will not emit when programmatically setting the value property.
true
ionFocusEmitted when the datetime has focus.true

方法

🌐 Methods

cancel

DescriptionEmits the ionCancel event and optionally closes the popover or modal that the datetime was presented in.
Signaturecancel(closeOverlay?: boolean) => Promise<void>
ParameterscloseOverlay: If true, closes the parent overlay. Defaults to false.

confirm

DescriptionConfirms the selected datetime value, updates the value property, and optionally closes the popover or modal that the datetime was presented in.
Signatureconfirm(closeOverlay?: boolean) => Promise<void>
ParameterscloseOverlay: If true, closes the parent overlay. Defaults to false.

reset

DescriptionResets the internal state of the datetime but does not update the value. Passing a valid ISO-8601 string will reset the state of the component to the provided date. If no value is provided, the internal state will be reset to the clamped value of the min, max and today.
Signaturereset(startDate?: string) => Promise<void>
ParametersstartDate: A valid ISO-8601 string to reset the datetime state to.

CSS 阴影部分

🌐 CSS Shadow Parts

NameDescription
calendar-dayThe individual buttons that display a day inside of the datetime calendar.
calendar-day activeThe currently selected calendar day.
calendar-day disabledThe calendar day that is disabled.
calendar-day todayThe calendar day that contains the current day.
calendar-days-of-weekThe container for the day-of-the-week header (both weekdays and weekends) when using a grid style layout.
calendar-headerThe calendar header manages the date navigation controls (month/year picker and previous/next buttons) and the days of the week when using a grid style layout.
datetime-headerThe datetime header contains the content for the title slot and the selected date.
datetime-selected-dateThe element that contains the selected date.
datetime-titleThe element that contains the title slot content.
month-year-buttonThe button that opens the month/year picker when using a grid style layout.
navigation-buttonThe buttons used to navigate to the next or previous month when using a grid style layout.
next-buttonThe button used to navigate to the next month when using a grid style layout.
previous-buttonThe button used to navigate to the previous month when using a grid style layout.
time-buttonThe button that opens the time picker when using a grid style layout with presentation="date-time" or "time-date".
time-button activeThe time picker button when the picker is open.
wheelThe wheel container when using a wheel style layout, or in the month/year picker when using a grid style layout.
wheel-itemThe individual items when using a wheel style layout, or in the month/year picker when using a grid style layout.
wheel-item activeThe currently selected wheel-item.

CSS 自定义属性

🌐 CSS Custom Properties

NameDescription
--backgroundThe primary background of the datetime component.
--background-rgbThe primary background of the datetime component in RGB format.
--title-colorThe text color of the title.
--wheel-fade-background-rgbThe color of the gradient covering non-selected items when using a wheel style layout, or in the month/year picker for grid style layouts. Must be in RGB format, e.g. 255, 255, 255.
--wheel-highlight-backgroundThe background of the highlight under the selected item when using a wheel style layout, or in the month/year picker for grid style layouts.
--wheel-highlight-border-radiusThe border radius of the highlight under the selected item when using a wheel style layout, or in the month/year picker for grid style layouts.

插槽

🌐 Slots

NameDescription
buttonsThe buttons in the datetime.
time-labelThe label for the time selector in the datetime.
titleThe title of the datetime.