• 【已解决】微信小程序-苹果手机日期解析异常


    在开发微信小程序时,使用了 uView 的 CountDown倒计时 组件和 uni.$u.timeFrom Api,后台传递了一个时间字符串,前台计算时间戳的差值,来显示还有多久开始,这个功能在模拟器和我自己手机(iphon13)上都是正常的,在提交测试之后,测试反馈(iphone12)日期显示异常,先后经历了三个版本的代码,最终解决了此问题。

    1 遇到的异常情况

    • 还有 0天 0小时 开始
    • NaN年前

    2 结论和解决方案

    • IOS 系统的部分版本不支持 yyyy-mm-dd 格式,需要将 - 替换为 /,即修改为 yyyy/mm/dd

    • IOS 系统的不同版本对 yyyy-mm-dd 格式的兼容性不同,iphone13 的 16.3 版本支持 yyyy-mm-dd

    • IOS 系统不支持日期的字符串拼接,如 new Date('2023-10-10 00:00:00').getTime(),如果需要设置年月日时分秒,可以使用 setHours 等方法

      const date = new Date("2023-10-10").getTime();
      date.setHours(0);
      
      • 1
      • 2

    3 代码示例

    // 项目开始时间,后台返回
    const startTime = "2023-10-12";
    
    // 第一版
    // 效果:12异常,13正常
    // iphone12 还有 0天 0小时 开始
    // iphone13 还有 1天 8小时 开始
    const beginTimeStamp = new Date(`${startTime} 00:00:00`).getTime();
    const currentTimeStamp = Date.now();
    const timePoint = beginTimeStamp - currentTimeStamp; // 传递给CountDown组件
    
    // 第二版
    // 效果:12正常,13异常
    // iphone12 还有 1天 8小时 开始
    // iphone13 还有 0天 0小时 开始
    const timeStr = startTime.replace(/-/g, "/"); // IOS不支持日期中的-,需要将-替换为/
    const beginTimeStamp = new Date(`${timeStr} 00:00:00`).getTime();
    const currentTimeStamp = Date.now();
    const timePoint = beginTimeStamp - currentTimeStamp;
    
    // 第三版
    // 效果:12和13都正常
    // iphone12 还有 1天 8小时 开始
    // iphone13 还有 1天 8小时 开始
    const timeStr = startTime.replace(/-/g, "/"); // IOS不支持日期中的-,需要将-替换为/
    const beginDate = new Date(timeStr);
    beginDate.setHours(0); // IOS不支持字符串拼接,需要调用setHours方法
    const currentTimeStamp = Date.now();
    const timePoint = beginTimeStamp - currentTimeStamp;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
  • 相关阅读:
    色氨酸乙酯双三氟甲基磺酰亚胺[TrpC2][Tf2N]离子液体
    帆软报表决策系统 上传excel文件
    如何使用进度猫甘特图制定项目计划
    JAVA学习------通配符参数
    C#基础入门教程-简介和环境
    TikTok+KOL:打造品牌种草的完美组合
    国家博物馆预约脚本(博物馆都行)
    Java核心知识点整理大全6-笔记
    专利-分析方法总结
    适用于物联网的UI设计工具都有哪些?
  • 原文地址:https://blog.csdn.net/qq_44212319/article/details/133762614