openharmony 鸿蒙 ts-basic-components-timepicker

2025-06-12 浏览 (1)

TimePicker

The TimePicker component allows users to select a time (with the hour and minute) from the given range.

NOTE

This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.

Child Components

Not supported

APIs

TimePicker(options?: TimePickerOptions)

Creates a time picker, which is in 24-hour format by default.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
optionsTimePickerOptionsNoParameters of the time picker.

TimePickerOptions

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
selectedDateNoTime of the selected item.
Default value: current system time
Since API version 10, this parameter supports two-way binding through $$.
Atomic service API: This API can be used in atomic services since API version 11.
format11+TimePickerFormatNoTime format.
Default value: TimePickerFormat.HOUR_MINUTE
Atomic service API: This API can be used in atomic services since API version 12.
start18+DateNoStart time of the time picker.
Default value: Date(0, 0, 0, 0, 0, 0); only the hour and minute settings take effect.
If both start and end are set to non-default values, the loop feature is disabled.
Atomic service API: This API can be used in atomic services since API version 18.
end18+DateNoEnd time of the time picker.
Default value: Date(0, 0, 0, 23, 59, 59); only the hour and minute settings take effect.
If both start and end are set to non-default values, the loop feature is disabled.
Atomic service API: This API can be used in atomic services since API version 18.

NOTE

Modifying the TimePickerOptions properties, such as selected, start, or end, during the scrolling process of the TimePicker component may not take effect. The Date object is used to handle dates and time.

Method 1: new Date ()

Obtains the current system date and time.

Method 2: new Date(value: number|string)

NameTypeMandatoryDescription
valuenumber |stringYesDate format.
number: number of milliseconds since 00:00:00 on January 1, 1970.
string: date string in formats such as 2025-02 2025-02-20 08:00:00 or 2025-02 2025-02-20T08:00:00.

Method 3: new Date(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number)

NameTypeMandatoryDescription
yearnumberYesYear. Example: 2025.
monthIndexnumberYesMonth index, for example, 2 for March.
datenumberNoDay of the month, for example, 10. (Required if hours is set.)
hoursnumberNoHour, for example, 15. (Required if minutes is set.)
minutesnumberNoMinute, for example, 20. (Required if seconds is set.)
secondsnumberNoSecond, for example, 20. (Required if ms is set.)
msnumberNoMillisecond, for example, 10.

TimePickerFormat11+

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameDescription
HOUR_MINUTEDisplay hours and minutes.
HOUR_MINUTE_SECONDDisplay hours, minutes, and seconds.

Handling in the case of exceptions

ExceptionResult
The start time is later than the end time.Both start time and end time are set to their default values.
The selected time is earlier than the start time.The selected time is set to the start time.
The selected time is later than the end time.The selected time is set to the end time.
The start time is later than the current system time, and the selected time is not set.The selected time is set to the start time.
The end time is earlier than the current system time, and the selected time is not set.The selected time is set to the end time.
The time format is invalid, such as '01:61:61'.The default value is used.

Attributes

In addition to the universal attributes, the following attributes are supported.

useMilitaryTime

useMilitaryTime(value: boolean)

Sets whether to display time in 24-hour format. When the display time is in 12-hour format, the AM/PM zone does not change depending on the hour portion.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valuebooleanYesWhether the display time is in 24-hour format.
Default value: false.
true: The display time is in 24-hour format.
false: The display time is in 12-hour format.

useMilitaryTime18+

useMilitaryTime(isMilitaryTime: Optional<boolean>)

Sets whether to display time in 24-hour format. Compared to useMilitaryTime, this API supports the undefined type for the isMilitaryTime parameter.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
isMilitaryTimeOptional<boolean>YesWhether the display time is in 24-hour format.
If isMilitaryTime is set to undefined, the default value false is used.
true: The display time is in 24-hour format.
false: The display time is in 12-hour format.

disappearTextStyle10+

disappearTextStyle(value: PickerTextStyle)

Sets the font color, font size, and font weight for the top and bottom items.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valuePickerTextStyleYesFont color, font size, and font weight of the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
}

disappearTextStyle18+

disappearTextStyle(style: Optional<PickerTextStyle>)

Sets the font color, font size, and font weight for the top and bottom items. Compared to disappearTextStyle10+, this API supports the undefined type for the style parameter.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
styleOptional<PickerTextStyle>YesFont color, font size, and font weight of the top and bottom items.
If style is set to undefined, the default value is used:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
}

textStyle10+

textStyle(value: PickerTextStyle)

Sets the font color, font size, and font weight for all items except the top, bottom, and selected items.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valuePickerTextStyleYesFont color, font size, and font weight of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
}

textStyle18+

textStyle(style: Optional<PickerTextStyle>)

Sets the font color, font size, and font weight for all items except the top, bottom, and selected items. Compared to textStyle10+, this API supports the undefined type for the style parameter.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
styleOptional<PickerTextStyle>YesFont color, font size, and font weight of all items except the top, bottom, and selected items.
If style is set to undefined, the default value is used:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
}

selectedTextStyle10+

selectedTextStyle(value: PickerTextStyle)

Sets the font color, font size, and font weight for the selected item.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valuePickerTextStyleYesFont color, font size, and font weight of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20fp',
weight: FontWeight.Medium
}
}

selectedTextStyle18+

selectedTextStyle(style: Optional<PickerTextStyle>)

Sets the font color, font size, and font weight for the selected item. Compared to selectedTextStyle10+, this API supports the undefined type for the style parameter.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
styleOptional<PickerTextStyle>YesFont color, font size, and font weight of the selected item.
If style is set to undefined, the default value is used:
{
color: '#ff007dff',
font: {
size: '20fp',
weight: FontWeight.Medium
}
}

loop11+

loop(value: boolean)

Sets whether to enable the loop mode.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valuebooleanYesWhether to enable the loop mode.
Default value: true.
The value true means to enable loop mode, and false means the opposite.

loop18+

loop(isLoop: Optional<boolean>)

Sets whether to enable the loop mode. Compared to loop11+, this API supports the undefined type for the isLoop parameter.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
isLoopOptional<boolean>YesWhether to enable the loop mode.
If isLoop is set to undefined, the default value true is used. The value true means to enable the loop mode, and false means the opposite.

dateTimeOptions12+

dateTimeOptions(value: DateTimeOptions)

Sets whether to display a leading zero for the hours, minutes, and seconds.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valueDateTimeOptionsYesWhether to display a leading zero for the hours, minutes, and seconds. Currently only the configuration of the hour, minute, and second parameters is supported.
Default value:
hour: In the 24-hour format, it defaults to "2-digit", which means a leading zero is used. In the 12-hour format, it defaults to "numeric", which means no leading zero is used.
minute: defaults to "2-digit", which means a leading zero is used.

dateTimeOptions18+

dateTimeOptions(timeFormat: Optional<DateTimeOptions>)

Sets whether to display a leading zero for the hours, minutes, and seconds. Compared to dateTimeOptions12+, this API supports the undefined type for the timeFormat parameter.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
timeFormatOptional<DateTimeOptions>YesWhether to display a leading zero for the hours, minutes, and seconds. Currently only the configuration of the hour, minute, and second parameters is supported.
Default value:
hour: In the 24-hour format, it defaults to "2-digit", which means a leading zero is used; in the 12-hour format, it defaults to "numeric", which means no leading zero is used.
minute: defaults to "2-digit", which means a leading zero is used.
second: defaults to "2-digit", which means a leading zero is used.
If hour, minute, or second is set to undefined, the display follows the default rules.

enableHapticFeedback12+

enableHapticFeedback(enable: boolean)

Sets whether to enable haptic feedback.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
enablebooleanYesWhether haptic feedback is enabled.
true (default): Haptic feedback is enabled.
false: Haptic feedback is disabled.
Whether this parameter takes effect after being set to true depends on hardware support.

enableHapticFeedback18+

enableHapticFeedback(enable: Optional<boolean>)

Sets whether to enable haptic feedback. Compared to enableHapticFeedback12+, this API supports the undefined type for the enable parameter.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
enableOptional<boolean>YesWhether haptic feedback is enabled.
If enable is set to undefined, the default value true is used. The value true means to enable haptic feedback, and false means the opposite.
Whether this parameter takes effect after being set to true depends on hardware support.

NOTE

To enable haptic feedback, you must declare the ohos.permission.VIBRATE permission under requestPermissions in the module.json5 file of the project.

"requestPermissions": [
{
 "name": "ohos.permission.VIBRATE",
}
]

enableCascade18+

enableCascade(enable: boolean)

Sets whether the AM/PM indicator automatically switches based on the hour in 12-hour format.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
enablebooleanYesWhether the AM/PM indicator automatically switches based on the hour in 12-hour format.
Default value: false. The value true means that the AM/PM indicator automatically switches based on the hour in 12-hour format, and false means the opposite.
Setting this parameter to true takes effect only when loop is also set to true.

digitalCrownSensitivity18+

digitalCrownSensitivity(sensitivity: Optional<CrownSensitivity>)

Sets the sensitivity to the digital crown rotation.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
sensitivityOptional<CrownSensitivity>YesSensitivity to the digital crown rotation.
Default value: CrownSensitivity.MEDIUM

NOTE

This API is only available to circular screens on wearable devices. The component needs to obtain focus before responding to the crown event.

Events

In addition to the universal events, the following events are supported.

onChange

onChange(callback: (value: TimePickerResult ) => void)

Triggered when a time is selected.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valueTimePickerResultYesTime in 24-hour format.

onChange18+

onChange(callback: Optional<OnTimePickerChangeCallback>)

Triggered when the time options in the TimePicker rest on the selected position after scrolling. Compared to onChange, this API supports the undefined type for the callback parameter.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
callbackOptional<OnTimePickerChangeCallback>YesCallback invoked when a time option is selected.
If callback is set to undefined, the callback function is not used.

onEnterSelectedArea18+

onEnterSelectedArea(callback: Callback<TimePickerResult>)

Triggered during the scrolling of the time picker when an item enters the divider area.

Compared to the onChange event, this event is triggered earlier, specifically when the scroll distance of the current column exceeds half the height of the selected item, which indicates that the item has entered the divider area. When enableCascade is set to true, using this callback is not recommended due to the interdependent relationship between the AM/PM and hour columns. This callback indicates the moment an option enters the divider area during scrolling, and only the value of the currently scrolled column will change. The values of other non-scrolled columns will remain unchanged.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
callbackCallback<TimePickerResult>YesCallback triggered during the scrolling of the time picker when an item enters the divider area.

OnTimePickerChangeCallback18+

type OnTimePickerChangeCallback = (value: TimePickerResult) => void

Triggered when a time is selected.

Widget capability: This API can be used in ArkTS widgets since API version 18.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valueTimePickerResultYesTime in 24-hour format.

TimePickerResult

Describes a time in 24-hour format.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeRead OnlyOptionalDescription
hournumberNoNoHour portion of the selected time.
Value range: [0-23]
minutenumberNoNoMinute portion of the selected time.
Value range: [0-59]
second11+numberNoNoSecond portion of the selected time.
Value range: [0-59]

Example

Example 1: Setting the Text Style

This example demonstrates how to configure disappearTextStyle, textStyle, and selectedTextStyle to customize the text style in a text picker.

// xxx.ets
@Entry
@Component
struct TimePickerExample {
  private selectedTime: Date = new Date('2022-07-22T08:00:00')

  build() {
    TimePicker({
      selected: this.selectedTime
    })
      .disappearTextStyle({ color: '#004aaf', font: { size: 24, weight: FontWeight.Lighter } })
      .textStyle({ color: Color.Black, font: { size: 26, weight: FontWeight.Normal } })
      .selectedTextStyle({ color: Color.Blue, font: { size: 30, weight: FontWeight.Bolder } })
      .onChange((value: TimePickerResult) => {
        if (value.hour >= 0) {
          this.selectedTime.setHours(value.hour, value.minute)
          console.info('select current date is: ' + JSON.stringify(value))
        }
      })
  }
}

timePicker

Example 2: Switching Between 12-Hour and 24-Hour Formats

This example demonstrates how to switch between 12-hour and 24-hour formats using useMilitaryTime.

// xxx.ets
@Entry
@Component
struct TimePickerExample {
  @State isMilitaryTime: boolean = false
  private selectedTime: Date = new Date('2022-07-22T08:00:00')

  build() {
    Column() {
      Button('Switch Time Format')
        .margin(30)
        .onClick(() => {
          this.isMilitaryTime = !this.isMilitaryTime
        })

      TimePicker({
        selected: this.selectedTime
      })
        .useMilitaryTime(this.isMilitaryTime)
        .onChange((value: TimePickerResult) => {
          if (value.hour >= 0) {
            this.selectedTime.setHours(value.hour, value.minute)
            console.info('select current time is: ' + JSON.stringify(value))
          }
        })
        .onEnterSelectedArea((value: TimePickerResult) => {
            console.info('item enter selected area, time is: ' + JSON.stringify(value))
        })
    }.width('100%')
  }
}

timePicker

Example 3: Setting the Time Format

This example shows how to set the time format using format and dateTimeOptions.

// xxx.ets
@Entry
@Component
struct TimePickerExample {
  private selectedTime: Date = new Date('2022-07-22T08:00:00')

  build() {
    Column() {
      TimePicker({
        selected: this.selectedTime,
        format: TimePickerFormat.HOUR_MINUTE_SECOND
      })
        .dateTimeOptions({ hour: "numeric", minute: "2-digit", second: "2-digit" })
        .onChange((value: TimePickerResult) => {
          if (value.hour >= 0) {
            this.selectedTime.setHours(value.hour, value.minute)
            console.info('select current date is: ' + JSON.stringify(value))
          }
        })
    }.width('100%')
  }
}

timePicker

Example 4: Setting Loopable Scrolling

This example demonstrates how to set whether scrolling is loopable using loop.

// xxx.ets
@Entry
@Component
struct TimePickerExample {
  @State isLoop: boolean = true
  private selectedTime: Date = new Date('2022-07-22T12:00:00')

  build() {
    Column() {
      TimePicker({
        selected: this.selectedTime
      })
        .loop(this.isLoop)
        .onChange((value: TimePickerResult) => {
          if (value.hour >= 0) {
            this.selectedTime.setHours(value.hour, value.minute)
            console.info('select current date is: ' + JSON.stringify(value))
          }
        })

      Row() {
        Text('Loopable scrolling').fontSize(20)

        Toggle({ type: ToggleType.Switch, isOn: true })
          .onChange((isOn: boolean) => {
            this.isLoop = isOn
          })
      }.position({ x: '60%', y: '40%' })

    }.width('100%')
  }
}

timePicker

Example 5: Setting the Start Time

This example demonstrates how to set the start time for the time picker.

// xxx.ets
@Entry
@Component
struct TimePickerExample {
  private selectedTime: Date = new Date('2022-07-22T08:50:00')

  build() {
    Column() {
      TimePicker({
        selected: this.selectedTime,
        format: TimePickerFormat.HOUR_MINUTE_SECOND,
        start: new Date('2022-07-22T08:30:00')
      })
        .dateTimeOptions({ hour: "numeric", minute: "2-digit", second: "2-digit" })
        .onChange((value: TimePickerResult) => {
          if (value.hour >= 0) {
            this.selectedTime.setHours(value.hour, value.minute)
            console.info('select current date is: ' + JSON.stringify(value))
          }
        })
    }.width('100%')
  }
}

timePicker

Example 6: Setting the End Time

This example demonstrates how to set the end time for the time picker.

// xxx.ets
@Entry
@Component
struct TimePickerExample {
  private selectedTime: Date = new Date('2022-07-22T08:50:00')

  build() {
    Column() {
      TimePicker({
        selected: this.selectedTime,
        format: TimePickerFormat.HOUR_MINUTE_SECOND,
        end: new Date('2022-07-22T15:20:00'),
      })
        .dateTimeOptions({ hour: "numeric", minute: "2-digit", second: "2-digit" })
        .onChange((value: TimePickerResult) => {
          if (value.hour >= 0) {
            this.selectedTime.setHours(value.hour, value.minute)
            console.info('select current date is: ' + JSON.stringify(value))
          }
        })
    }.width('100%')
  }
}

timePicker

Example 7: Enabling the AM/PM Indicator to Automatically Switch Based on the Hour in 12-hour Format

This example demonstrates how to enable AM/PM indicator to automatically switch based on the hour in 12-hour format using enableCascade and loop.

// xxx.ets
@Entry
@Component
struct TimePickerExample {
  private selectedTime: Date = new Date('2022-07-22T08:00:00')

  build() {
    Column() {
      TimePicker({
        selected: this.selectedTime,
      })
        .enableCascade(true)
        .loop(true)
        .onChange((value: TimePickerResult) => {
          if (value.hour >= 0) {
            this.selectedTime.setHours(value.hour, value.minute)
            console.info('select current date is: ' + JSON.stringify(value))
          }
        })
    }.width('100%')
  }
}

timePicker

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArcButton

harmony 鸿蒙ArcSlider

harmony 鸿蒙Chip

harmony 鸿蒙ChipGroup

harmony 鸿蒙ComposeListItem

harmony 鸿蒙ComposeTitleBar

harmony 鸿蒙advanced.Counter

harmony 鸿蒙Dialog Box (Dialog)

harmony 鸿蒙DialogV2

harmony 鸿蒙DownloadFileButton

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/ayzTav