计算时间差,页面倒计时,安卓与ios兼容问题

前言

在开发一些有关商品交易类的项目时,多半会遇到活动倒计时之类的需求,最近也是在小程序中遇到,实现方法很多,但是在小程序中遇到ios和安卓的兼容问题,所以记录下来

代码

/**
   * timestampSwitch - 根据对比传入的两个时间戳,计算出相差的时分秒
   *
   * @param{String}startTimestamp 计算起始时间戳,默认是当前时间
   * @param{Number}endTimestamp 计算结束时间(当前接受的是时间字符串,如2018-11-30 23:59:59)
   * @return{Object}
   */
  const timestampSwitch = (endTimestamp, startTimestamp = (new Date()).valueOf()) => {
    if (!Number(endTimestamp) || !Number(startTimestamp)) console.error('Incorrect parameter');
    // 兼容ios
    let et = Date.parse(endTimestamp) || Date.parse(endTimestamp.replace(/-/g, '/'));
    // 计算
    let difference = (endTimestamp - startTimestamp),
        timeDifference = (difference > 0 ? difference : 0) / 1000,
        days = parseInt(timeDifference / 86400),
        hours = parseInt((timeDifference % 86400) / 3600),
        minutes = parseInt((timeDifference % 3600) / 60),
        seconds = parseInt(timeDifference % 60);

    return {
      days,
      hours,
      minutes,
      seconds
    }
  };

问题

问题在于后台给我的是时间字符串,我们需要转为时间戳后计算,但是安卓和ios转换时会有不同如上代码
iOSDate.parse(endTimestamp)转为时间戳会报错,兼容性方法Date.parse(endTimestamp.replace(/-/g, '/'))

本文转载于:猿2048→https://www.mk2048.com/blog/blog.php?id=hi2b1k1cbab

猜你喜欢

转载自www.cnblogs.com/homehtml/p/12684989.html