HarmonyOS 自定义格式化时间日期?

想将当前时间转化成自定义时间格式,xxxx中调用方法是

SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.getDefault());
阅读 585
1 个回答

可以使用三方库dayjs,下载安装:ohpm install dayjs。

使用: import dayjs from “dayjs”;

当前时间:dayjs().format(“YYYY-MM-DD HH:mm:ss”)

某个date: dayjs(date).format(“YYYY-MM-DD HH:mm:ss”)

可参考以下文档:https://gitee.com/openharmony-tpc/openharmony\_tpc\_samples/tree/master/dayjs

示例demo:

import dayjs from "dayjs";

@Entry
@Component
struct Index {
  @State timeStr: number = 1714991876;
  @State timeNow: string = ''

  build() {
    Row() {
      Column() {
        Text('当前时间:'+ this.timeNow).fontSize(20).fontWeight(FontWeight.Bold).width("100%")
        Button("get time").onClick(() => {
          try {
            this.timeNow = dayjs.unix(this.timeStr).format('YYYY-MM-DD HH:mm:ss')
          } catch (e) {
          }
        })
      }.justifyContent(FlexAlign.Center).width('100%')
    }.height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进