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
相关问题
获取系统当前时间异常
1408浏览 • 1回复 待解决
如何获取当前系统时间时间
2555浏览 • 1回复 待解决
HarmonyOS 获取时间
1407浏览 • 1回复 待解决
HarmonyOS 获取18位随机数没有生效
1112浏览 • 1回复 待解决
HarmonyOS 获取时间问题
1749浏览 • 1回复 待解决
HarmonyOS 代码混淆配置没有生效
1006浏览 • 1回复 待解决
如何获取系统时间,你知道吗?
4717浏览 • 1回复 待解决
HarmonyOS 如何获取当前时间时间
1433浏览 • 1回复 待解决
如何获取系统时间以及格式的转换
4181浏览 • 1回复 待解决
HarmonyOS 时间时间
1267浏览 • 1回复 待解决
如何获取今天的日期、时间
1756浏览 • 1回复 待解决
HarmonyOS 时间运用
2247浏览 • 1回复 待解决
HarmonyOS 时间转换
1175浏览 • 1回复 待解决
HarmonyOS 转化时间
1246浏览 • 1回复 待解决
HarmonyOS 时间如何转换为时间
867浏览 • 1回复 待解决