Date基本使用一

1.函数getIntv,获取从当前时间到指定日期的间隔时间

function getIntv(timeString){
   var now=new Date();
   var target=new Date(timeString);
   var gap=(target-now)/1000;
   var day=parseInt(gap/3600/24);
   var hour=parseInt(gap/3600%24);
   var minute=parseInt(gap/60%60);
   var second=parseInt(gap%60);
   return "距"+timeString+"还有"+day+"天"+hour+"小时"+minute+"分钟"+second+"秒"
 }
var str = getIntv("2017-01-08");
console.log(str);

2.数字日期转化为中文日期

var chStr=["零","一","二","三","四","五","六","七","八","九","十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六",  "二十七", "二十八", "二十九", "三十", "三十一"]
function getChsDate(timeStr){
    var time=new Date(timeStr);
    var year =time.getFullYear()+"";
    var month=time.getMonth()+1+"";
    var date=time.getDate()+"";
    return chStr[year[0]]+chStr[year[1]]+chStr[year[2]]+chStr[year[3]]+"年"+chStr[month]+"月"+chStr[date]+"日";
}

var str = getChsDate('2015-01-08');
console.log(str); 

3.获取N天前的日期

function getLastNDays(num){
  var now=Date.now();
  var distance=new Date(now-num*24*3600*1000);
  var year=distance.getFullYear();
  var month=distance.getMonth()+1;
  var day=distance.getDate();
  var getd=year+"-"+month+"-"+day;
  return getd;  
}

var lastWeek =  getLastNDays(7); // ‘2016-01-08’
var lastMonth = getLastNDays(30); //'2015-12-15'

4.计算一个程序的执行时间

var Runtime = (function(){
    var startTime,endTime,getTime;
    var obj = {
        start: function(){
             startTime=Date.now();
        },
        end: function(){
             endTime=Date.now();
        },
        get: function(){
          return getTime=endTime-startTime;
        }
    };
return obj;
}());
Runtime.start();
for(var i=0;i<10000;i++){
  console.log();
}
Runtime.end();
console.log(Runtime.get());

你可能感兴趣的:(Date基本使用一)