HarmonyOS 获取系统时间戳没有生效

参考代码如下:

let dateStr = '' 
    try { 
      //取日期时间戳 
      systemDateTime.getCurrentTime(true, (error, time) => { 
        if (error) { 
          console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); 
          return; 
        } 
        dateStr = time.toString(); 
      }); 
    } catch(e) { 
      console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); 
    }
HarmonyOS
2024-11-08 08:58:22
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get
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}`); 
          } 
        }) 
    }.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(); 
      let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); 
      // time = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + second; 
      time = '' + year + month + day  + hour  + min  + second; 
      console.log(date + "转换===>" + time); 
      AlertDialog.show({ message: str + "时间戳转===>" + time }) 
    } catch (e) { 
      console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); 
    } 
    return time; 
  } 
}
分享
微博
QQ
微信
回复
2024-11-08 17:25:12
相关问题
如何获取当前系统时间时间
976浏览 • 1回复 待解决
获取系统当前时间异常
232浏览 • 1回复 待解决
HarmonyOS 获取时间
33浏览 • 1回复 待解决
HarmonyOS 代码混淆配置没有生效
42浏览 • 1回复 待解决
如何获取系统时间,你知道吗?
2926浏览 • 1回复 待解决
HarmonyOS 获取时间问题
0浏览 • 1回复 待解决
如何获取系统时间以及格式的转换
2021浏览 • 1回复 待解决
HarmonyOS 如何获取当前时间时间
48浏览 • 1回复 待解决
如何获取今天的日期、时间
604浏览 • 1回复 待解决
HarmonyOS 时间转换
38浏览 • 1回复 待解决
HarmonyOS 转化时间
16浏览 • 1回复 待解决
HarmonyOS 时间运用
970浏览 • 1回复 待解决