目前HarmonyOS 没有直接格式化的api,针对时间戳格式化现有两种解决方案:第一种:自定义方法获取时间戳内的年月日小时分钟秒,然后进行字符串的拼接返回。完整代码如下:import systemDateTime from '@ohos.systemDateTime'; import { BusinessError } from '@ohos.base'; @Entry @Component struct Index5 { @State timeStr : string = ''; build() { Flex( { direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Text(`当前时间:`+this.timeStr) .fontSize(20) .fontWeight(FontWeight.Bold) Button("get time") .width(100) .height(100).onClick(()=>{ //同步方法获取系统时间戳 try { let time = systemDateTime.getTime(false) this.timeStr = this.getTimeToYYYYDDMMHHMMSS(time) }catch (e){ let error = e as BusinessError; console.info(`Failed to get time. message: ${error.message}, code: ${error.code}`); } //异步方法获取系统时间戳 try { systemDateTime.getCurrentTime(false,(error,time)=>{ if (error) { console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`) return; } console.info(`Succeeded in getting currentTime : ${time}`); this.timeStr = this.getTimeToYYYYDDMMHHMMSS(time) }) AlertDialog.show({message:'sss'}); }catch (e){ console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); } }) } .width('100%') .height('100%') } //将时间戳转换成日期格式 getTimeToYYYYDDMMHHMMSS(str: number): string { let time: string = ""; console.log(str.toString()) let date = new Date(str); console.log(JSON.stringify(date)) try { let year = date.getFullYear(); let month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1); let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); let min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes第二种使用第三方库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 } }三方库的下载使用参考链接:https://gitee.com/openharmony-tpc/openharmony\_tpc\_samples/tree/master/dayjs
目前HarmonyOS 没有直接格式化的api,针对时间戳格式化现有两种解决方案:
第一种:自定义方法获取时间戳内的年月日小时分钟秒,然后进行字符串的拼接返回。完整代码如下:
第二种使用第三方库dayjs,完整代码如下:
三方库的下载使用参考链接:
https://gitee.com/openharmony-tpc/openharmony\_tpc\_samples/tree/master/dayjs