js小程序ios日期解析失败NAN兼容

小程序中ios使用 new Date() 的时候,如果有 “-”分隔符,将会解析失败

如果日期过短也会解析失败,比如只有 2022-08,年月这样也解析不出来,

下面工具能解决上述问题,但是在手动创建字符串时间,建议使用 2022/08/01 ,斜杠等方式,需要组件展示的时候再用工具转换

  format(date, fmt) {

    if (typeof date === 'string') {
      // ios 解析不出来 年月 2020-05
      if (date.length < 8) {
        date = `${date}-1`;
      }
      date = new Date(date.replace(/-/g, '/').replace('T', ' ')).getTime();
    }
    date = new Date(date);
    const o = {
      'M+': date.getMonth() + 1, // 月份
      'd+': date.getDate(), // 日
      'h+': date.getHours(), // 小时
      'm+': date.getMinutes(), // 分
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      S: date.getMilliseconds(), // 毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      );
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        );
    }
    return fmt;
  },
};

版权声明:本文为wapchief原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。