元服务:index.ets[时辰时刻案例注释]

2024-11-11 22:04:30
15次阅读
0个评论
最后修改时间:2024-11-11 22:07:00

import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
//导包
//引入路由包
import { router } from '@kit.ArkUI'

@Entry
@Component
struct Index {
  //定义文本变量
  @State message: string = '现代时辰时刻';
  //定义一个Date对象,
  @State base_time: Date = new Date(Date.now());
  //定义一个时间字符串,并规定格式
  @State str_time: string =
    this.formatTime(this.base_time.getHours().toString() + ":" + this.base_time.getMinutes() + ":" + this.base_time.getSeconds());
  //
  @State show_change_time: string = this.getShiChen(this.base_time.getHours(),this.base_time.getMinutes());
  @State isf : boolean = true;
  //开始建筑  ---给一样式
  build() {
//相对布局的Div容器
    RelativeContainer() {
      Row(){
        Button("跳转到第二个页面")
          .width('100%')
          .height('15%')
          .margin({top:500})
          .fontSize(30)
          .onClick(()=>{
            //写路由跳转
            router.pushUrl({url:"pages/SecondPage"})

        })
      }
      Row() {
        //函数调用对象
        Text(this.message)
          //给一个id名
          .id('shiChenShiKe')
          //字体大小
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          //布局位置
          .alignRules({
            center: { anchor: '__container__', align: VerticalAlign.Center },
            middle: { anchor: '__container__', align: HorizontalAlign.Center }
          }).fontColor(Color.Brown)
        //给一个id名,布局位置,
      }.id('row1').margin({ top: 50 }).justifyContent(FlexAlign.Center).width('100%')

      //开始走
      Row() {
        //调用另一个对象,调资本字体
        Text(this.str_time).fontSize(35).fontColor(Color.Black).fontWeight(FontWeight.Bolder)
      }//布局,颜色
      .backgroundColor('#66CCDD')
      .id('row2')
      .margin({ top: 150 })
      .justifyContent(FlexAlign.Center)
      .width('100%')

      //时辰对象
      Row() {
        Text(this.show_change_time).fontSize(40).fontColor(Color.Black).fontWeight(FontWeight.Bolder)
      }
      .backgroundColor('#66CCDD')
      .id('row3')
      .margin({ top: 250 })
      .justifyContent(FlexAlign.Center)
      .width('100%')

      //调用按钮函数,更改样式
      Row() {                                                     // 当点击的时候
        Button('校准时间').size({ width: 250, height: 80 }).fontSize(30).onClick(() => {
          //进行判断
          if(this.isf){
            this.isf = false;
            setInterval(()=>{this.show_change_time = this.Time_Change_Time();},1000);
          }
        }).id("btn1").width('100%')
      }.id('row4').margin({ top: 350 }).width('100%')
    }
    .height('100%')
    .width('100%')
  }

  //定义更改时间的方法
  Time_Change_Time():string{
    let timeInMs = Date.now();
    let dateObj = new Date(timeInMs);
    //通过 dateObj拼一个当前时间的日期字符串--作为formatTime的参数调用该方法,
    //返回给之前的时间,对他重新规定
    this.str_time = this.formatTime(dateObj.getHours() + ":" + dateObj.getMinutes() + ":" + dateObj.getSeconds());
    //将新的  hour  和 minutes 传给 getShiChen(),
    return this.getShiChen(dateObj.getHours(), dateObj.getMinutes());
  }
  //规定时间用的方法 含参方法有返回值  --参数是一个时间字符串
  formatTime(timeStr: string): string {
    //通过‘:’ 来分割,识别hour  min s
    let timeParts = timeStr.split(':');
    // timeParts (数组) 调用 map方法,
    //对每个元素进行判断,对应输出n个新的元素
    let formattedParts = timeParts.map((part) => {
      // 每一个元素先转化成int类型,
      let num = parseInt(part);
      // 当 num<10 返回值前加个0
      return num < 10? `0${num}` : `${num}`;
    });
    //这里是 拼“ : ”
    return formattedParts.join(':');
  }
  //日志相关信息
  aboutToAppear() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    this.loginWithHuaweiID();
  }

  //根据传入的小时,输出小时的时辰
  convertToChineseTimes(hour: number): string {

    if (23 <= hour || hour < 1) {
      return "子时";
    } else if (1 <= hour && hour < 3) {
      return "丑时";
    } else if (3 <= hour && hour < 5) {
      return "寅时";
    } else if (5 <= hour && hour < 7) {
      return "卯时";
    } else if (7 <= hour && hour < 9) {
      return "辰时";
    } else if (9 <= hour && hour < 11) {
      return "巳时";
    } else if (11 <= hour && hour < 13) {
      return "午时";
    } else if (13 <= hour && hour < 15) {
      return "未时";
    } else if (15 <= hour && hour < 17) {
      return "申时";
    } else if (17 <= hour && hour < 19) {
      return "酉时";
    } else if (19 <= hour && hour < 21) {
      return "戌时";
    } else {
      return "亥时";
    }
  }

  convertToChineseTime(hour: number, minute: number): string {

    let chineseHour = this.convertToChineseTimes(hour);
    //第二个字
    let minuteMark = hour % 2 !== 0 ? "上" : "下";
    //根据minute判断输出分
    if (minute < 15) {
      minuteMark += "一刻";
    } else if (minute < 30) {
      minuteMark += "二刻";
    } else if (minute < 45) {
      minuteMark += "三刻";
    } else {
      minuteMark += "四刻";
    }
    //
    return `${chineseHour}${minuteMark}`;
  }

  getShiChen(hour: number, minute: number): string {
    return this.convertToChineseTime(hour, minute);
  }
  /**
   * Sample code for using HUAWEI ID to log in to atomic service.
   * According to the Atomic Service Review Guide, when a atomic service has an account system,
   * the option to log in with a HUAWEI ID must be provided.
   * The following presets the atomic service to use the HUAWEI ID silent login function.
   * To enable the atomic service to log in successfully using the HUAWEI ID, please refer
   * to the HarmonyOS HUAWEI ID Access Guide to configure the client ID and fingerprint certificate.
   */
  private loginWithHuaweiID() {
    //获取连接
    // Create a login request and set parameters
    let loginRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
    // Whether to forcibly launch the HUAWEI ID login page when the user is not logged in with the HUAWEI ID
    loginRequest.forceLogin = false;
    // Execute login request
    let controller = new authentication.AuthenticationController();
    //执行连接
    controller.executeRequest(loginRequest).then((data) => {
      let loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
      let authCode = loginWithHuaweiIDResponse.data?.authorizationCode;
      // Send authCode to the backend in exchange for unionID, session

    }).catch((error: BusinessError) => {
      //异常执行
      hilog.error(0x0000, 'testTag', 'error: %{public}s', JSON.stringify(error));
      if (error.code == authentication.AuthenticationErrorCode.ACCOUNT_NOT_LOGGED_IN) {
        // HUAWEI ID is not logged in, it is recommended to jump to the login guide page
      }
    });
  }
}



PixPin_2024-11-11_22-03-19.png

收藏00

登录 后评论。没有帐号? 注册 一个。