目录

元服务基于系统时制显示时间

问题现象

元服务中如何基于系统时制(12小时制/24小时制)显示时间?

背景知识

元服务中支持使用is24HourClock接口判断系统时制是否为24小时制。

TextClock组件通过文本将当前系统时间显示在设备上,可以通过format属性设置时间格式。

解决方案

在组件生命周期回调中查询系统时制,比如aboutToAppear、onPageShow,将查询的结果应用于时间显示格式中,示例代码如下:

import { i18n } from '@kit.LocalizationKit';


@Entry
@Component
struct Index {
  // 创建 TextClock 控制器
  private controller: TextClockController = new TextClockController();
  @State format: string = 'HH:mm:ss';
  @State timeText: string = '';


  aboutToAppear(): void {
    this.format = this.textClockFormat();
    this.timeText = this.formatTimestamp();
  }


  onPageShow(): void {
    this.format = this.textClockFormat();
    this.timeText = this.formatTimestamp();
  }


  textClockFormat(): string {
    if (i18n.System.is24HourClock()) {
      return 'HH:mm:ss'; // 24小时制,如:17:00:04
    }
    return 'aa hh:mm:ss'; // 12小时制,如:上午 5:00:04
  }


  formatTimestamp(timestamp: number = new Date().getTime()): string {
    if (i18n.System.is24HourClock()) {
      return this.timestampToLocale(timestamp, false);
    }
    return this.timestampToLocale(timestamp, true);
  }


  timestampToLocale(timestamp: number, isHour12: boolean) {
    // 创建Date对象
    const date = new Date(timestamp);
    const options: Intl.DateTimeFormatOptions = {
      hour: 'numeric',
      minute: '2-digit',
      second: '2-digit',
      hour12: isHour12
    };
    return date.toLocaleString('zh-CN', options);
  }


  build() {
    Navigation() {
      Column() {
        Row() {
          Text('实时时间:')
            .fontSize(20);
          // 使用 TextClock 组件实时显示系统时间
          TextClock({ timeZoneOffset: -8, controller: this.controller })
            .format(this.format) // 设置时间格式
            .fontSize(20);
        };


        Row() {
          Text('固定时间:')
            .fontSize(20);
          // 使用 TextClock 组件实时显示系统时间
          Text(this.timeText)
            .fontSize(20);
        };
      }
      .width('100%')
      .height('50%')
      .justifyContent(FlexAlign.Center);
    }
    .title('根据系统时制显示时间:');
  }
}