Skip to main content
Version: v6

ion-datetime

shadow

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

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.

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 Datetime Format: YYYY-MM-DDTHH:mmZ

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.

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

DescriptionFormatDatetime Value Example
YearYYYY1994
Year and MonthYYYY-MM1994-12
Complete DateYYYY-MM-DD1994-12-15
Date and TimeYYYY-MM-DDTHH:mm1994-12-15T13:47
UTC TimezoneYYYY-MM-DDTHH:mm:ssZ1994-12-15T13:47:20Z
Timezone OffsetYYYY-MM-DDTHH:mm:ssTZD1994-12-15T13:47:20+05:00
Hour and MinuteHH:mm13:47

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

While seconds, milliseconds, and time zone can be specified using the ISO 8601 datetime format, ion-datetime does not provide an interface for second, millisecond, and time zone selection. Any second, millisecond, or time zone values provided will be ignored.

Basic Usage

Usage with 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.

Date Constraints

Max and Min Dates

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.

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

Selecting Specific Values

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.

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

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.

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 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

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

The time label is not automatically localized. See Time Label for more information.

Hour Cycle

ion-datetime will use the hour cycle that is specified by the locale property by default. For example, if locale is set to en-US, then ion-datetime will use a 12 hour cycle.

There are 4 primary hour cycle types:

Hour cycle typeDescription
'h12'Hour system using 1–12; corresponds to 'h' in patterns. The 12 hour clock, with midnight starting at 12:00 am.
'h23'Hour system using 0–23; corresponds to 'H' in patterns. The 24 hour clock, with midnight starting at 0:00.
'h11'Hour system using 0–11; corresponds to 'K' in patterns. The 12 hour clock, with midnight starting at 0:00 am.
'h24'Hour system using 1–24; corresponds to 'k' in pattern. The 24 hour clock, with midnight starting at 24:00.

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.

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

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

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 also supports locale extension tags as part of the Intl.Locale API. These tags let you encode information about the locale in the locale string itself. Developers may prefer to use the extension tag approach if they are using the Intl.Locale API in their apps.

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

Be sure to check the Browser Compatibility Chart for Intl.Locale before using it in your app.

Presentation

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.

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 and year selection is available by passing month-year, year-month, month, or year to the presentation property.

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

Time Selection

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

This example shows a datetime with the time configuration.

Date Selection

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

This example shows a datetime with the date configuration.

Wheel Style Pickers

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.

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.

presentationHas Grid Style?Has Wheel Style?
dateYesYes
date-timeYesYes
monthNoYes
month-yearNoYes
timeNoYes
time-dateYesYes
yearNoYes

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

Multiple Date Selection

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

This property is only supported when using presentation="date" and preferWheel="false".

Titles

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

Buttons

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

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

Customizing Button Texts

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-datetime has confirm, cancel, and reset methods that developers can call when clicking on custom buttons. The reset method also allows developers to provide a date to reset the datetime to.

Highlighting Specific Dates

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.

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

This property is only supported when preferWheel="false", and using a presentation of either "date", "date-time", or "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.

Theming

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.

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

Time Zones

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.

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

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 = dateFnsTz.utcToZonedTime(date, userTimeZone);

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

Parsing Date Values

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.

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

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

Advanced Datetime Validation and Manipulation

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 Navigation

ion-datetime has full keyboard support for navigating between focusable elements inside of the component. The following table details what each key does:

KeyFunction
TabMoves focus to the next focusable element.
Shift + TabMoves focus to the previous focusable element.
Space or EnterClicks the focusable element.

Date Grid

KeyFunction
ArrowUpMoves focus to the same day of the previous week.
ArrowDownMoves focus to the same day of the next week.
ArrowRightMoves focus to the next day.
ArrowLeftMoves focus to the previous day.
HomeMoves focus to the first day of the current week.
EndMoves focus to the last day of the current week.
PageUpChanges the grid of dates to the previous month.
PageDownChanges the grid of dates to the next month.
Shift + PageUpChanges the grid of dates to the previous year.
Shift + PageDownChanges the grid of dates to the next year.

Time, Month, and Year Wheels

When using the time wheel picker, you can use the number keys to select hour and minute values when the columns are focused.

KeyFunction
ArrowUpScroll to the previous item.
ArrowDownScroll to the next item.
HomeScroll to the first item.
EndScroll to the last item.

Interfaces

DatetimeChangeEventDetail

interface DatetimeChangeEventDetail {
value?: string | null;
}

DatetimeCustomEvent

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

Descriptionピッカーのキャンセルボタンに表示するテキストです。
Attributecancel-text
Typestring
Default'Cancel'

clearText

Descriptionピッカーの"Clear"ボタンに表示するテキストです。
Attributeclear-text
Typestring
Default'Clear'

color

Descriptionアプリケーションのカラーパレットから使用する色を指定します。デフォルトのオプションは以下の通りです。 "primary", "secondary", "tertiary", "success", "warning", "danger", "light", "medium", と "dark" です.色に関する詳しい情報は theming を参照してください。
Attributecolor
Type"danger" | "dark" | "light" | "medium" | "primary" | "secondary" | "success" | "tertiary" | "warning" | string & Record<never, never> | undefined
Default'primary'

dayValues

Description選択可能な日のリストを作成するために使用する値です。デフォルトでは、指定した月のすべての曜日が表示されます。しかし、表示する曜日を正確に制御するために、dayValues には数値、数値の配列、またはコンマで区切られた数値の文字列を取ることができます。配列のdayが2月の31のように選択した月にとって無効な数字であっても、選択した月にとって有効でない日は正しく表示されないことに注意してください。
Attributeday-values
Typenumber | number[] | string | undefined
Defaultundefined

disabled

Descriptiontrueの場合、ユーザはdatetimeを操作することができません。
Attributedisabled
Typeboolean
Defaultfalse

doneText

Descriptionピッカーの "Done "ボタンに表示するテキスト。
Attributedone-text
Typestring
Default'Done'

firstDayOfWeek

Descriptionion-datetimeに使用する週の最初の曜日を指定します。デフォルト値は 0` で、日曜日を表す。
Attributefirst-day-of-week
Typenumber
Default0

highlightedDates

Description特定の日付にカスタムテキストと背景色を適用するために使用します。 ISO 文字列と色を含むオブジェクトの配列、または ISO 文字列を受け取って色を返すコールバックのいずれかを指定します。 preferWheel="false"を持つ datedate-timetime-date` のプレゼンテーションにのみ適用されます。
Attributeundefined
Type((dateIsoString: string) => DatetimeHighlightStyle | undefined) | DatetimeHighlight[] | undefined
Defaultundefined

hourCycle

Descriptionion-datetime`の時間周期を指定します。値が設定されていない場合、現在のロケールによって指定される。
Attributehour-cycle
Type"h12" | "h23" | undefined
Defaultundefined

hourValues

Description選択可能な時間のリストを作成するために使用される値です。デフォルトでは、24時間制の場合は 0 から 23 まで、12時間制の場合は 1 から 12 までの時間帯が設定されます。しかし、表示する時間を正確に制御するために、hourValues には数値、数値の配列、またはコンマで区切られた数値の文字列を指定することができます。
Attributehour-values
Typenumber | number[] | string | undefined
Defaultundefined

isDateEnabled

Description個々の日付(暦日)が有効か無効かを返します。 trueの場合、その日は有効/対話型になる。もし false ならば、その日は無効/非インタラクティブです。 この関数は、指定された日のISO 8601の日付文字列を受け取ります。デフォルトでは、すべての曜日が有効になります。開発者はこの関数を使用して、特定の日を無効にするカスタムロジックを記述することができます。 この関数は、レンダリングされたカレンダーの各日、前月、当月、翌月に対して呼び出されます。カスタム実装は、ジャンクを避けるためにパフォーマンスを最適化する必要があります。
Attributeundefined
Type((dateIsoString: string) => boolean) | undefined
Defaultundefined

locale

Descriptionion-datetimeに使用するロケールを指定します。これは月と日の名前のフォーマットに影響します。'default'値は、あなたのデバイスが設定するデフォルトのロケールを参照します。
Attributelocale
Typestring
Default'default'

max

Description許容される最大のdatetimeを指定します。値は、ISO 8601 datetime format standard1996-12-19 に従った日付文字列である必要があります。このフォーマットは、正確な日付時刻を指定する必要はありません。例えば、最大で1994のような年号を指定することができます。デフォルトはこの年の末日です。
Attributemax
Typestring | undefined
Defaultundefined

min

Description許容される最小のdatetime。値は ISO 8601 datetime format standard に従った日付文字列でなければならず、例えば 1996-12-19 のようなものです。このフォーマットは、正確な日付時刻を指定する必要はありません。例えば、最小値は1994のような年号だけでいいです。デフォルトは、今日から100年前の年頭です。
Attributemin
Typestring | undefined
Defaultundefined

minuteValues

Description選択可能な分数のリストを作成するために使用される値です。デフォルトでは、分数は 0 から 59 までの範囲です。しかし、表示する分を正確に制御するために、minuteValues には数値、数値の配列、またはコンマで区切られた数値の文字列を取ることができます。例えば、分表示を15分ごとに行う場合は、 minuteValues="0,15,30,45" と入力することになります。
Attributeminute-values
Typenumber | number[] | string | undefined
Defaultundefined

mode

Descriptionmodeは、どのプラットフォームのスタイルを使用するかを決定します。
Attributemode
Type"ios" | "md"
Defaultundefined

monthValues

Description選択可能な月のリストを作成するために使用する値。デフォルトでは、月の値は 1 から 12 までの範囲です。しかし、どの月を表示するかを正確に制御するために、monthValues には数値、数値の配列、またはコンマで区切られた数値の文字列を取ることができます。例えば、夏の月だけを表示する場合、この入力値は monthValues="6,7,8" となります。つまり、1月の値は 1 であり、12月の値は 12 です。
Attributemonth-values
Typenumber | number[] | string | undefined
Defaultundefined

multiple

Descriptiontrueの場合、複数の日付を一度に選択することができる。presentation="date"preferWheel="false"` にのみ適用される。
Attributemultiple
Typeboolean
Defaultfalse

name

Descriptionフォームデータとともに送信されるコントロールの名前。
Attributename
Typestring
Defaultthis.inputId

preferWheel

Descriptiontrueの場合、可能な限りカレンダーグリッドの代わりにホイールピッカーが表示されます。もし false ならば、可能な限りホイールピッカーの代わりにカレンダーグリッドがレンダリングされます。 ホイールピッカーは、presentationが以下の値の場合、グリッドの代わりにレンダリングすることができます。presentation'date', 'date-time', または 'time-date'. ホイールピッカーは、preferWheelの値に関係なく、presentationが次の値のいずれかである場合に常にレンダリングされます。'time', 'month', 'month-year', または 'year'`.
Attributeprefer-wheel
Typeboolean
Defaultfalse

presentation

Descriptionどの値を選択するか。'date'はカレンダーピッカーを表示し、月、日、年を選択します。'time'は時間ピッカーを表示し、時、分、そして(オプションで)AM/PMを選択します。date-time'は日付ピッカーを最初に表示し、時間ピッカーを次に表示します。'time-date'`は時間ピッカーを最初に、日付ピッカーを2番目に表示します。
Attributepresentation
Type"date" | "date-time" | "month" | "month-year" | "time" | "time-date" | "year"
Default'date-time'

readonly

Descriptiontrueの場合、datetimeは正常に表示されるが、インタラクティブにはなりません。
Attributereadonly
Typeboolean
Defaultfalse

showClearButton

Descriptiontrueの場合、ion-datetimeコンポーネントの下部にあるデフォルトの "Cancel "と "OK "ボタンと一緒に "Clear "ボタンがレンダリングされます。これらのボタンをカスタマイズしたい場合、開発者は button slotを使用することもできる。カスタムボタンが button slotに設定されている場合、デフォルトのボタンはレンダリングされません。
Attributeshow-clear-button
Typeboolean
Defaultfalse

showDefaultButtons

Descriptiontrueの場合、ion-datetimeコンポーネントの下部にデフォルトの "Cancel" と "OK" ボタンがレンダリングされます。これらのボタンをカスタマイズしたい場合は、buttonslotを使用することもできます。カスタムボタンが button slotに設定されている場合、デフォルトのボタンはレンダリングされません。
Attributeshow-default-buttons
Typeboolean
Defaultfalse

showDefaultTimeLabel

Descriptiontrueの場合、ion-datetimeコンポーネントの時間セレクタにデフォルトの "Time "ラベルがレンダリングされる。このラベルをカスタマイズしたい場合は、time-labelslotを使用することもできます。 time-label slotにカスタムラベルが設定されている場合、デフォルトのラベルはレンダリングされません。
Attributeshow-default-time-label
Typeboolean
Defaulttrue

showDefaultTitle

Descriptiontrueの場合、カレンダーピッカーの上にヘッダーが表示されます。これには、slotされたタイトルと、選択された日付の両方が含まれます。
Attributeshow-default-title
Typeboolean
Defaultfalse

size

Descriptioncoverの場合、ion-datetimeはコンテナの全幅を覆うように展開される。fixedの場合、ion-datetime`は固定幅になる。
Attributesize
Type"cover" | "fixed"
Default'fixed'

titleSelectedDatesFormatter

Description選択された日付の数を示すヘッダーテキストをフォーマットするために使用されるコールバックです。選択された日付が0または1以上の場合のみ使用されます(つまり、ちょうど1の場合は未使用です)。デフォルトでは、ヘッダーテキストは "numberOfDates days "に設定されています。
Attributeundefined
Type((selectedDates: string[]) => string) | undefined
Defaultundefined

value

Descriptiondatetimeの値を有効なISO 8601 datetime文字列として指定します。multiple="true"`の場合は、文字列の配列とする必要がある。
Attributevalue
Typenull | string | string[] | undefined
Defaultundefined

yearValues

Description選択可能な年号のリストを作成するために使用する値。デフォルトでは、年の値は minmax の間の範囲になります。しかし、表示する年を正確に制御するために、yearValues には数値、数値の配列、またはカンマで区切られた数値の文字列を取ることができます。例えば、今後のうるう年と最近のうるう年を表示するには、この入力の値は yearValues="2024,2020,2016,2012,2008" となります。
Attributeyear-values
Typenumber | number[] | string | undefined
Defaultundefined

Events

NameDescription
ionBlurdatetimeのフォーカスが外れたときに発行されます。
ionCanceldatetimeの選択がキャンセルされたときに発生します。
ionChange値(選択された日付)が変化したときに発行されます。
ionFocusdatetimeにフォーカスが当たったときに発行されます。

Methods

cancel

DescriptionionCancel イベントを発行し、オプションで datetime が表示されたポップオーバーまたはモーダルを閉じます。
Signaturecancel(closeOverlay?: boolean) => Promise<void>

confirm

Description選択されたdatetimeの値を確認し、valueプロパティを更新し、オプションでdatetimeが表示されていたポップオーバーまたはモーダルを閉じます。
Signatureconfirm(closeOverlay?: boolean) => Promise<void>

reset

Descriptiondatetimeの内部状態をリセットするが、値は更新しない。有効なISO-8601文字列を渡すと、コンポーネントの状態は指定した日付にリセットされます。値が提供されない場合、内部状態はmin、max、todayのクランプされた値にリセットされます。
Signaturereset(startDate?: string) => Promise<void>

CSS Shadow Parts

No CSS shadow parts available for this component.

CSS Custom Properties

NameDescription
--backgrounddatetimeコンポーネントの主な背景。
--background-rgbdatetimeコンポーネントの主な背景をRGBフォーマットで示します。
--title-colorタイトルの文字色です。

Slots

NameDescription
buttonsdatetimeのボタンです。
time-labeldatetimeの時間セレクタのラベルです。
titledatetimeのタイトルです。