运行uni-app鸿蒙模拟器 使用new Date().getTime() 获取到的时间不正确
运行uni-app鸿蒙模拟器 使用new Date().getTime() 获取到的时间不正确
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Mac | 14.3.1 (23D60) | HBuilderX |
产品分类:uniapp/App
PC开发环境操作系统:Mac
HBuilderX类型:Alpha
HBuilderX版本号:4.52
手机系统:HarmonyOS NEXT
手机系统版本号:HarmonyOS NEXT Developer Preview
手机厂商:模拟器
手机机型:模拟器 HarmonyOS 版本5.0.0
页面类型:vue
vue版本:vue3
打包方式:云端
示例代码:
new Date().getTime()
操作步骤:
new Date().getTime()
预期结果:
当前时间
实际结果:
拿到的时间比当前时间早13个小时多
bug描述:
new Date().getTime()
拿到的时间戳预期得到1739252633000 (2025年2月11日13:43) (ios, andriod, h5都能正常拿到准确的时间)
运行到鸿蒙 拿不到准确的时间,拿到的错误时间如下
实际拿到的数据时间戳为1739199018967(2025-02-10 22:50:18)
更多关于运行uni-app鸿蒙模拟器 使用new Date().getTime() 获取到的时间不正确的实战教程也可以访问 https://www.itying.com/category-93-b0.html
忽略-鸿蒙模拟器时间不对
更多关于运行uni-app鸿蒙模拟器 使用new Date().getTime() 获取到的时间不正确的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
这个时间差异问题很可能是由于鸿蒙模拟器的时区设置不正确导致的。在鸿蒙模拟器中,new Date().getTime()
获取的是UTC时间戳,但模拟器可能没有正确应用本地时区偏移。
建议的解决方案:
-
检查模拟器的时区设置是否正确(中国标准时区应该是UTC+8)
-
可以尝试使用以下代码获取更准确的时间:
const now = new Date();
const offset = now.getTimezoneOffset() * 60 * 1000; // 获取时区偏移
const correctTime = now.getTime() - offset; // 修正后的时间戳
-
或者使用第三方库如moment.js或day.js来处理时间,它们能更好地处理时区问题
-
也可以考虑使用uni-app提供的API获取时间:
uni.getSystemInfo({
success: function(res) {
console.log(res.timezone); // 检查时区信息
}
});