HarmonyOS 时间戳运用

想要实现的场景:

1.获取当前时间的时间戳;

2.历史的时间戳和当前时间戳对比,得出差距的小时数;

3. 获取某个月最初的时间戳和最终的时间戳。

HarmonyOS
2024-08-29 09:47:54
1881浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
superinsect

可以使用systemDateTime.getCurrentTime的方法获取当前系统时间的Unix时间戳,

参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-date-time-V5

文档说说明的Unix纪元以来经过的时间就是当前系统时间的Unix时间戳

您还可以用第三方库dayjs,将时间戳格式化后再进行比较,参考链接:

https://gitee.com/openharmony-tpc/openharmony_tpc_samples/tree/master/dayjs

示例如下:

import dayjs from "dayjs"; 
 
@Entry 
@Component 
struct Index { 
  @State timeStr : number = 1318781876; 
  @State timeNow: string = '' 
  build() { 
    Row() { 
      Column() { 
        Text(`当前时间:`+this.timeNow) 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .width("100%") 
        Button("get time") 
          .onClick(() => { 
            try { 
              this.timeNow = this.getTimeToYYYYDDMMHHMMSS(this.timeStr) 
            } 
            catch (e) { 
            } 
          }) 
      } 
      .justifyContent(FlexAlign.Center) 
      .width('100%') 
    } 
    .height('100%') 
  } 
 
  getTimeToYYYYDDMMHHMMSS(str: number): string { 
    let time:string ='' 
    time = dayjs.unix(1318781876).format('YYYY-MM-DD HH:mm:ss') 
    return time 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
分享
微博
QQ
微信
回复
2024-08-29 18:15:26


相关问题
HarmonyOS 时间时间
997浏览 • 1回复 待解决
HarmonyOS 时间转换
852浏览 • 1回复 待解决
HarmonyOS 获取时间
1035浏览 • 1回复 待解决
HarmonyOS 转化时间
929浏览 • 1回复 待解决
HarmonyOS 获取时间问题
1172浏览 • 1回复 待解决
HarmonyOS 如何获取当前时间时间
1015浏览 • 1回复 待解决
HarmonyOS 时间如何转换为时间
648浏览 • 1回复 待解决
HarmonyOS 转换时间的方法
1285浏览 • 1回复 待解决
HarmonyOS 时间格式化
1078浏览 • 1回复 待解决
如何获取当前系统时间时间
1947浏览 • 1回复 待解决
HarmonyOS timestamp转换为正常时间
692浏览 • 1回复 待解决
获取系统当前时间异常
1001浏览 • 1回复 待解决
如何获取今天的日期、时间
1402浏览 • 1回复 待解决
HarmonyOS 获取系统时间没有生效
1095浏览 • 1回复 待解决
HarmonyOS 如何将时间格式化
978浏览 • 1回复 待解决
如何将时间转换为日期格式的时间
4309浏览 • 1回复 待解决
如何获取系统时间,你知道吗?
3951浏览 • 1回复 待解决
如何获取系统时间以及格式的转换
3118浏览 • 1回复 待解决