实现倒计时(天数、时、分、秒)

parseInt() 函数可解析一个字符串,并返回一个整数。

<body onload="leftTimer()"> 
  
<h2>剩余时间:</h2> 
<div id="timer"></div> 
</body> 
<script language="javascript" type="text/javascript">  
function leftTimer(year,month,day,hour,minute,second){ 
  var leftTime = (new Date(year,month-1,day,hour,minute,second)) - (new Date()); //计算剩余的毫秒数 
  var days = parseInt(leftTime / 1000 / 60 / 60 / 24 , 10); //计算剩余的天数 
  var hours = parseInt(leftTime / 1000 / 60 / 60 % 24 , 10); //计算剩余的小时 
  var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 
  var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 
  days = checkTime(days); 
  hours = checkTime(hours); 
  minutes = checkTime(minutes); 
  seconds = checkTime(seconds); 
  setInterval("leftTimer(2016,11,11,11,11,11)",1000); 
  document.getElementById("timer").innerHTML = days+"天" + hours+"小时" + minutes+"分"+seconds+"秒";  
} 
function checkTime(i){ //将0-9的数字前面加上0,例1变为01 
  if(i<10) 
  { 
    i = "0" + i; 
  } 
  return i; 
} 
  
</script>
  function formatTime(ms) {
      ms = new Date("2018/8/8 14:20:00").getTime() - Date.now();
      if(ms <= 0){
        document.getElementById("showTime").innerHTML = '已结束'
        window.cancelAnimationFrame(animate);
        return ;
      }
      var ss = 1000;
      var mi = ss * 60;
      var hh = mi * 60;
      var dd = hh * 24;

      var day = parseInt(ms / dd);
      var hour = parseInt((ms - day * dd) / hh);
      var minute = parseInt((ms - day * dd - hour * hh) / mi);
      var second = parseInt((ms - day * dd - hour * hh - minute * mi) / ss);
      var milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

      let sb = '';
      if (day >= 0) {
        sb += day + "天"
      }
      if (hour >= 0) {
        /* if(hour >= 0 && hour <= 9){
          sb = sb + '0' + hour + ":"
        }else{
          sb += hour + ":" 
        } */
        sb = hour > 9 ? sb + hour + ":" : sb + '0' + hour + ":"
      }
      if (minute >= 0) {
        sb = minute > 9 ? sb + minute + ":" : sb + '0' + minute + ":"
      }
      if (second >= 0) {
        sb = second > 9 ? sb + second + ":" : sb + '0' + second + ":"
      }
      if (milliSecond >= 0) {
        sb += parseInt(milliSecond / 100)
      }
      document.getElementById("showTime").innerHTML = '距结束' + sb
      animate = window.requestAnimationFrame(formatTime);
    }
    // window.requestAnimationFrame(formatTime)
    var animate;
    formatTime();

抢购倒计时功能

<SCRIPT LANGUAGE="JavaScript">
function _fresh()
{
 var endtime=new Date("2017/4/23,19:33:12");
 var nowtime = new Date();
 var leftsecond=parseInt((endtime.getTime()-nowtime.getTime())/1000);
 __d=parseInt(leftsecond/3600/24);
 __h=parseInt((leftsecond/3600)%24);
 __m=parseInt((leftsecond/60)%60);
 __s=parseInt(leftsecond%60);
var c=new Date();
var q=((c.getMilliseconds())%10);
 document.getElementById("times").innerHTML=__d+"天 "+__h+"小时"+__m+"分"+__s+"."+q+"秒";
 if(leftsecond<=0){
 document.getElementById("times").innerHTML="抢购已结束";
 clearInterval(sh);
 }
}
_fresh()
var sh;
sh=setInterval(_fresh,100);
</SCRIPT>

抢购倒计时

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title>团购、定时抢购倒计时 </title> 
<meta http-equiv="content-type" content="text/html; charset=gb2312" /> 
<meta name="keywords" content="" /> 
<meta name="description" content="" /> 
<script language="JavaScript"> 
var tms = []; 
var day = []; 
var hour = []; 
var minute = []; 
var second = []; 
function takeCount() { 
setTimeout("takeCount()", 1000); 
for (var i = 0, j = tms.length; i < j; i++) { 
//计数减一 
tms[i] -= 1000; 
//计算时分秒 
var days = Math.floor(tms[i] / (1000 * 60 * 60 * 24)); 
var hours = Math.floor(tms[i] / (1000 * 60 * 60)) % 24; 
var minutes = Math.floor(tms[i] / (1000 * 60)) % 60; 
var seconds = Math.floor(tms[i] / 1000) % 60; 
if (days < 0) 
days = 0; 
if (hours < 0) 
hours = 0; 
if (minutes < 0) 
minutes = 0; 
if (seconds < 0) 
seconds = 0; 
//将时分秒插入到html中 
document.getElementById(day[i]).innerHTML = days; 
document.getElementById(hour[i]).innerHTML = hours; 
document.getElementById(minute[i]).innerHTML = minutes; 
document.getElementById(second[i]).innerHTML = seconds; 
} 
} 
setTimeout("takeCount()", 1000); 
</script> 
</head> 
<body> 
<div> 
<ul> 
<li style="width: 300px;">剩余时间: <span id="d1" style="font-weight: bold">0</span> <span> 
天 </span><span id="h1" style="font-weight: bold">0</span> <span>小时 </span><span id="m1" 
style="font-weight: bold">0</span> <span>分 </span><span id="s1" style="font-weight: bold"> 
0</span> <span>秒</span></li> 
<script type="text/javascript"> 
tms[tms.length] = "168935343345"; 
day[day.length] = "d1"; 
hour[hour.length] = "h1"; 
minute[minute.length] = "m1"; 
second[second.length] = "s1"; 
</script> 
<li style="width: 300px;">剩余时间: <span id="d2" style="font-weight: bold">0</span> <span> 
天 </span><span id="h2" style="font-weight: bold">0</span> <span>小时 </span><span id="m2" 
style="font-weight: bold">0</span> <span>分 </span><span id="s2" style="font-weight: bold"> 
0</span> <span>秒</span></li> 
<script type="text/javascript"> 
tms[tms.length] = "1689353433455"; 
day[day.length] = "d2"; 
hour[hour.length] = "h2"; 
minute[minute.length] = "m2"; 
second[second.length] = "s2"; 
</script> 
</ul> 
</div> 
</body> 
</html> 

倒计时 x 天 x 时 x 分 x 秒效果

<script>
 (function () {
  var tian = document.getElementsByClassName('JS-tian')[0];
  var shi = document.getElementsByClassName('JS-shi')[0];
  var fen = document.getElementsByClassName('JS-fen')[0];
  var miao = document.getElementsByClassName('JS-miao')[0];
  var endTime = new Date('2117/07/12 23:59:59').getTime() + 1000;
  var interval = null;
  interval = setInterval(function () {
   var syhm = endTime - Date.now(); // 剩余毫秒
   if (syhm >= 0) {
    tian.innerText = Math.floor(syhm / 1000 / 60 / 60 / 24);
    shi.innerText = Math.floor(syhm / 1000 / 60 / 60 % 24);
    fen.innerText = Math.floor(syhm / 1000 / 60 % 60);
    miao.innerText = Math.floor(syhm / 1000 % 60);
   } else {
    clearInterval(interval);
   }
  }, 0);
 })();
</script>

前端技术前沿8_其他分类

<head>
<meta charset="UTF-8">
<title>简单时长倒计时</title>
<SCRIPT type="text/javascript">        
            var maxtime = 60 * 60; //一个小时,按秒计算,自己调整!   
            function CountDown() {
                if (maxtime >= 0) {
                    minutes = Math.floor(maxtime / 60);
                    seconds = Math.floor(maxtime % 60);
                    msg = "距离结束还有" + minutes + "分" + seconds + "秒";
                    document.all["timer"].innerHTML = msg;
                    if (maxtime == 5 * 60)alert("还剩5分钟");
                        --maxtime;
                } else{
                    clearInterval(timer);
                    alert("时间到,结束!");
                }
            }
            timer = setInterval("CountDown()", 1000);                
        </SCRIPT>
</head>

前端技术前沿8_其他分类_02

<head>  
    <meta charset="UTF-8">  
    <title>js简单时分秒倒计时</title>  
    <script type="text/javascript">  
        function countTime() {  
            //获取当前时间  
            var date = new Date();  
            var now = date.getTime();  
            //设置截止时间  
            var str="2017/5/17 00:00:00";
            var endDate = new Date(str); 
            var end = endDate.getTime();  
            
            //时间差  
            var leftTime = end-now; 
            //定义变量 d,h,m,s保存倒计时的时间  
            var d,h,m,s;  
            if (leftTime>=0) {  
                d = Math.floor(leftTime/1000/60/60/24);  
                h = Math.floor(leftTime/1000/60/60%24);  
                m = Math.floor(leftTime/1000/60%60);  
                s = Math.floor(leftTime/1000%60);                     
            }  
            //将倒计时赋值到div中  
            document.getElementById("_d").innerHTML = d+"天";  
            document.getElementById("_h").innerHTML = h+"时";  
            document.getElementById("_m").innerHTML = m+"分";  
            document.getElementById("_s").innerHTML = s+"秒";  
            //递归每秒调用countTime方法,显示动态时间效果  
            setTimeout(countTime,1000);  
  
        }  
    </script>  
</head >  
<body onload="countTime()" >  
    <div>  
        <span id="_d">00</span>  
        <span id="_h">00</span>  
        <span id="_m">00</span>  
        <span id="_s">00</span>  
    </div>  
</body> 

毫秒转天时分秒的实例

formatDuring: function(mss) {
  var days = parseInt(mss / (1000 * 60 * 60 * 24));
  var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = (mss % (1000 * 60)) / 1000;
  return days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 ";
}

将毫秒转换成‘天时分秒

formatTime(time) {

    var days = parseInt(time / (1000 * 60 * 60 * 24));

    var hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

    var minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));

    var seconds = Math.floor((time % (1000 * 60)) / 1000);

    this.setData({

      days,

      hours,

      minutes,

      seconds

    })

  }
formatTime(msTime) {

    let time = msTime /1000;

    let day = Math.floor(time /60 /60 /24);

    let hour = Math.floor(time /60 /60) %24;

    let minute = Math.floor(time /60) %60;

    let second = Math.floor(time) %60;

    return `${day}天${hour}时${minute}分${second}秒`

}

小程序

Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    countdown:''
,    endDate2: '2018-08-08 11:41:00'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.countTime()
  },
  countTime() {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.endDate2);//设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差                              
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      ms = ms < 100 ? "0" + ms : ms
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      that.setData({
        countdown: d + ":" + h + ":" + m + ":" + s + ":" + ms,
      })
     //递归每秒调用countTime方法,显示动态时间效果
    setTimeout(that.countTime, 100);
    } else {
      console.log('已截止')
      that.setData({
        countdown:'00:00:00'
      })
    }
   
  },
})

动态显示项目倒计时

// 倒计时
function countdown(that) {
  var EndTime = new Date(that.data.collage.collage_end).getTime() || [];
  // console.log(EndTime);
  var NowTime = new Date().getTime();
  var total_micro_second = EndTime - NowTime || [];   //单位毫秒
  if (total_micro_second < 0) {
    // console.log('时间初始化小于0,活动已结束状态');
    total_micro_second = 1;     //单位毫秒 ------  WHY?
  }
  // console.log('剩余时间:' + total_micro_second);
  // 渲染倒计时时钟
  that.setData({
    clock: dateformat(total_micro_second)   //若已结束,此处输出'0天0小时0分钟0秒'
  });
  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止"
    });
    return;
  }
  setTimeout(function () {
    total_micro_second -= 1000;
    countdown(that);
  }
    , 1000)
}
 
// 时间格式化输出,如11天03小时25分钟19秒  每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60);
  return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
}
Page({
    onLoad: function(options) {
        wx.request({
            success: function(request) {
                // 倒计时(获取结束时间后再进行倒计时方法调用)
                countdown(that);
            }
        })
    }   
})

毫秒级倒计时,时分秒

Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    countdown:''
,    endDate2: '2018-08-08 11:41:00'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.countTime()
  },
  countTime() {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.endDate2);//设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差                              
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      ms = ms < 100 ? "0" + ms : ms
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      that.setData({
        countdown: d + ":" + h + ":" + m + ":" + s + ":" + ms,
      })
     //递归每秒调用countTime方法,显示动态时间效果
    setTimeout(that.countTime, 100);
    } else {
      console.log('已截止')
      that.setData({
        countdown:'00:00:00'
      })
    }
   
  },
})

倒计时实现实例

function countdown(that) {
 var second = that.data.second
 if (second == 0) {
 // console.log("Time Out...");
 that.setData({
 second: "Time Out..."
 });
 return ;
 }
 var time = setTimeout(function(){
 that.setData({
 second: second - 1
 });
 countdown(that);
 }
 ,1000)
}
  
Page({
 data: {
 second: 3
 },
 onLoad: function() {
 countdown(this);
 }
});

微信小程序倒计时
工具

//util.js
 
//取倒计时(天时分秒)
function getTimeLeft(datetimeTo){
  // 计算目标与现在时间差(毫秒)
  let time1 = new Date(datetimeTo).getTime();
  let time2 = new Date().getTime();
  let mss = time1 - time2;
   
  // 将时间差(毫秒)格式为:天时分秒
  let days = parseInt(mss / (1000 * 60 * 60 * 24));
  let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = parseInt((mss % (1000 * 60)) / 1000);
   
  return days + "天" + hours + "时" + minutes + "分" + seconds + "秒"
}
 
module.exports = {
  getTimeLeft: getTimeLeft
}

逻辑

//index.js
 
const util = require('../../utils/util.js')
 
Page({
  data: {
    datetimeTo: "2019/01/01 10:30:00 GMT+0800", // 秒杀开始时间
    timeLeft: ""    // 剩下的时间(天时分秒)
  },
  onShow: function () {
    this.data.timer = setInterval(() =>{ //注意箭头函数!!
      this.setData({
        timeLeft: util.getTimeLeft(this.data.datetimeTo)//使用了util.getTimeLeft
      });
      if (this.data.timeLeft == "0天0时0分0秒") {
        clearInterval(this.data.timer);
      }
    }, 1000);
  }
});

js毫秒数转天时分秒:

formatDuring: function(mss) {
     var days = parseInt(mss / (1000 * 60 * 60 * 24));
     var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
     var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
     var seconds = (mss % (1000 * 60)) / 1000;
     return days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 ";
}

时间戳的转换及调用
前端技术前沿8_其他分类_03

小程序内部

function formatTime(time) {
 if(typeof time !== 'number' || time < 0) {
  return time
 }
var hour = parseInt(time / 3600)
 time = time % 3600
 var minute = parseInt(time/60)
 time = parseInt(time%60)
 var second = time
 return ([hour, minute, second]).map(function (n){
 n = n.toString()
 return n[1] ? n : '0' + n
 }).join(':')
}
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
/**
 * 时间戳转化为年 月 日 时 分 秒
 * ts: 传入时间戳
 * format:返回格式,支持自定义,但参数必须与formateArr里保持一致
*/
function tsFormatTime(timestamp, format) {

    const formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    let returnArr = [];

    let date = new Date(timestamp);
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    let second = date.getSeconds()
    returnArr.push(year, month, day, hour, minute, second);

    returnArr = returnArr.map(formatNumber);

    for (var i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;

}

前端技术前沿8_其他分类_04

js毫秒转换天时分秒/动态倒计时

<script language="JavaScript">
  
  function getQueryString(name) {
    var reg =new RegExp("(^|&)"+ name +"=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r !=null) return unescape(r[2]); returnnull;
  }

  var currentDate = new Date();
  var strEndTime = getQueryString("EndTime");
  var EndTime=new Date(strEndTime);
  
  var days= EndTime - currentDate; 
  EndTimeMsg = parseInt(days / 1000);//精确到秒

  function show() {
    h = Math.floor(EndTimeMsg / 60 / 60);
    m = Math.floor((EndTimeMsg - h * 60 * 60) / 60);
    s = Math.floor((EndTimeMsg - h * 60 * 60 - m * 60));
    document.getElementById("DD").innerHTML = parseInt(h/24);
    document.getElementById("HH").innerHTML = h;
    document.getElementById("MM").innerHTML = m;
    document.getElementById("SS").innerHTML = s;
    EndTimeMsg--;
    if (EndTimeMsg < 0)
    {
        document.getElementById("DD").innerHTML = "0";
        document.getElementById("HH").innerHTML = "00";
        document.getElementById("MM").innerHTML = "00";
        document.getElementById("SS").innerHTML = "00";;
    }
  }
  setInterval("show()", 1000)
  
</script>

前端技术前沿8_其他分类_05

// 转化时分秒
export function formatTime(time) {
  let times = {}
  let hours = parseInt(time / 1000 / 60 / 60, 10)
  let minutes = parseInt((time / 1000 / 60) % 60, 10)
  let seconds = parseInt((time / 1000) % 60, 10)
  times = {
    h: hours < 10 ? '0' + hours : hours,
    m: minutes < 10 ? '0' + minutes : minutes,
    s: seconds < 10 ? '0' + seconds : seconds
  }
  return times
}
export function formatTimeGroup(time) {
  if (time <= 0) {
    return { hours: '00', minutes: '00', seconds: '00' }
  }
  let times = {}
  let leftTime = time / 1000

  let hours = parseInt(leftTime / 60 / 60, 10)
  let minutes = parseInt((leftTime / 60) % 60, 10)
  let seconds = parseInt(leftTime % 60, 10)

  times.hours = hours >= 10 ? hours : '0' + hours
  times.minutes = minutes >= 10 ? minutes : '0' + minutes
  times.seconds = seconds >= 10 ? seconds : '0' + seconds

  return times
}
import Config from '../utils/config.js'
var CryptoJS = require('crypto-js')

export function formartToDay(str) {
  let formatStr = ''
  let date = new Date(str)
  let Y = date.getFullYear()
  let M =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  let h =
    date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
  let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  formatStr = M + '月' + D + '日' + ' ' + h + m
  formatStr = Y + '-' + M + '-' + D
  return formatStr
}
export function formartToDayPoint(str) {
  let formatStr = ''
  let date = new Date(str)
  let Y = date.getFullYear()
  let M =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  // let h =
  //   date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
  // let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  formatStr = Y + '.' + M + '.' + D
  return formatStr
}
export function formartToTime(str) {
  let formatStr = ''
  let date = new Date(str)
  let Y = date.getFullYear()
  let M =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  let h =
    date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
  let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  formatStr = Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
  return formatStr
}

export function format(time, type = 1, needSecond = true) {
  let date = time ? new Date(time) : new Date()
  let Y = date.getFullYear()
  let M =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  let h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  let resultTime = ''
  switch (type) {
    case 1:
      resultTime = `${Y}年${M}月${D}日${h}时${m}分${needSecond ? `${s}秒` : ''}`
      break
    case 2:
      resultTime = `${Y}/${M}/${D} ${h}:${m}${needSecond ? `:${s}` : ''}`
      break
    case 3:
      resultTime = `${Y}-${M}-${D} ${h}:${m}${needSecond ? `:${s}` : ''}`
      break
    case 4:
      resultTime = `${('' + Y).substr(2, 2)}年${M}月${D}日${h}时${m}分${
        needSecond ? `${s}秒` : ''
        }`
      break
    case 5:
      resultTime = `${('' + Y).substr(2, 2)}-${M}-${D} ${h}:${m}${
        needSecond ? `:${s}` : ''
        }`
      break
    case 6:
      resultTime = `${('' + Y).substr(2, 2)}/${M}/${D} ${h}:${m}${
        needSecond ? `:${s}` : ''
        }`
      break
    case 7:
      resultTime = `${('' + Y).substr(2, 2)}/${M}/${D}`
      break
    case 8:
      resultTime = `${Y}-${M}-${D}`
      break
    case 9:
      resultTime = `${Y}.${M}.${D}`
      break
    default:
      break
  }
  return resultTime
}

export function uploader(path, callBack) {
  var datastring = 'applet/' + new Date().getTime().toString()
  var name = path.split('.')
  var type = name[name.length - 1]
  datastring = datastring + '.' + type
  console.log('util.js=>uploader=>type', type)
  wx.uploadFile({
    url: Config.imgUploadUrl,
    filePath: path,
    name: 'file',
    header: { 'Content-Type': 'multipart/form-data' },
    formData: {
      name: path,
      policy:
        'eyJleHBpcmF0aW9uIjoiMjAyMC0wMS0wMVQxMjowMDowMC4wMDBaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF1dfQ==',
      OSSAccessKeyId: 'LTAIhp4ZzzU2LhIp',
      signature: 'EP+fLiwXi9cO/EVyinFUkc94cC8=',
      key: datastring,
      success_action_status: '200'
    },
    success: function (_res) {
      var imgUrl = `${Config.imgUploadUrl}/${datastring}`
      console.log('util.js=>uploader=>imgUrl', imgUrl)
      callBack && callBack(imgUrl)
    },
    fail: function (res) {
      console.log('util.js=>uploader=>fail', res)
    }
  })
}

export function isCardNo(card) {
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (reg.test(card) === false) {
  }
}

// 查看物流时使用   时间格式  20180207150436
export function formatterDateTime() {
  var date = new Date()
  var month = date.getMonth() + 1
  var datetime =
    date.getFullYear() +
    '' + // "年"
    (month >= 10 ? month : '0' + month) +
    '' + // "月"
    (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) +
    '' +
    (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) +
    '' +
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
    '' +
    (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
  return datetime
}

// 转化时分秒
export function formatTime(time) {
  let times = {}
  let hours = parseInt(time / 1000 / 60 / 60, 10)
  let minutes = parseInt((time / 1000 / 60) % 60, 10)
  let seconds = parseInt((time / 1000) % 60, 10)
  times = {
    h: hours < 10 ? '0' + hours : hours,
    m: minutes < 10 ? '0' + minutes : minutes,
    s: seconds < 10 ? '0' + seconds : seconds
  }
  return times
}

export function checkUpdateApplet() {
  if (!wx.getUpdateManager) {
    return
  }
  const updateManager = wx.getUpdateManager()
  updateManager.onUpdateReady(() => {
    wx.showModal({
      title: '更新提示',
      content: '更好玩更好吃的新版本,了解一下?',
      showCancel: false,
      success: _ => {
        updateManager.applyUpdate()
      }
    })
  })
}

// DES 加密
export function encryptByDES(message) {
  var key = '$7%9R5Hh&yGDt'
  var keyHex = CryptoJS.enc.Utf8.parse(key)
  var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    mode: CryptoJS.mode.ECB
    // padding: CryptoJS.pad.Zero
  })
  return encrypted.toString()
}

export function formatTimeGroup(time) {
  if (time <= 0) {
    return { hours: '00', minutes: '00', seconds: '00' }
  }
  let times = {}
  let leftTime = time / 1000

  let hours = parseInt(leftTime / 60 / 60, 10)
  let minutes = parseInt((leftTime / 60) % 60, 10)
  let seconds = parseInt(leftTime % 60, 10)

  times.hours = hours >= 10 ? hours : '0' + hours
  times.minutes = minutes >= 10 ? minutes : '0' + minutes
  times.seconds = seconds >= 10 ? seconds : '0' + seconds

  return times
}

 

前端技术前沿8_其他分类_06