Skip to main content
Version: v7 (beta)

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

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 & Record<never, never> ๏ฝœ 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

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"h12" ๏ฝœ "h23" ๏ฝœ 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.
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.
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 is not interactive.
Attributereadonly
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".
Attributeundefined
Type((selectedDates: string[]) => string) ๏ฝœ undefined
Defaultundefined

value

DescriptionThe value of the datetime as a valid ISO 8601 datetime string. Should be an array of strings if 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="2024,2020,2016,2012,2008".
Attributeyear-values
Typenumber ๏ฝœ number[] ๏ฝœ string ๏ฝœ undefined
Defaultundefined

Events

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

Methods

cancel

DescriptionEmits the ionCancel event and optionally closes the popover or modal that the datetime was presented in.
Signaturecancel(closeOverlay?: boolean) => Promise<void>

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>

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>

CSS Shadow Parts

No CSS shadow parts available for this component.

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.

Slots

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