HarmonyOS 鸿蒙Next ArkUI-X 如何获取时间戳

发布于 1周前 作者 yibo5220 来自 鸿蒙OS

HarmonyOS 鸿蒙Next ArkUI-X 如何获取时间戳

我想要以同步方式获取“自Unix纪元以来经过的时间”。原本我使用 @ohos.systemDateTime 中的 systemDateTime.getTime(false),但是在 ArkUI-X 中提升此 API 在跨平台框架无法使用。即使强行编译也没有用。

cke_3841.png

cke_4122.png

有没有什么其他方法可以让我同步获取时间戳。

3 回复

解决措施:

在HarmonyOS中使用接口@ohos.systemTime的getCurrentTime来获取系统系统时间和时区。在Openharmony中使用@ohos.systemDateTime的getCurrentTime来获取系统系统时间和时区。

使用接口@ohos.systemTime:

  

try { systemTime.getCurrentTime(true, (error, time) => { if (error) { console.info(`Failed to getting currentTime. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting currentTime: ${time}`); });} catch(e) { console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`);}

使用@ohos.systemDateTime接口:

  

try { systemDateTime.getCurrentTime(true, (error, time) => { if (error) { console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting currentTime : ${time}`); }); } catch(e) { console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); }

const now = new Date();
const timestamp = now.getTime(); //获取时间戳

在HarmonyOS鸿蒙Next ArkUI-X中,获取时间戳可以通过JavaScript的Date对象实现。具体方法是使用Date.now()来获取当前时间的毫秒级时间戳。如果ArkUI-X环境支持更丰富的API,也可以使用@ohos.systemTime.getCurrentTime@ohos.systemDateTime.getCurrentTime等系统接口获取系统时间,然后转换为时间戳。如果问题依旧没法解决,请加我微信,我的微信是itying888。

回到顶部