Date使用总结

获取日期的指定部分:

var date =new Date(); //获取日期对象
console.log(date.getFullYear() + "年");//获取年
console.log((date.getMonth() + 1) + "月");//获取月函数默认是0~11 所以要+1
console.log(date.getdateate() + "日");//获取日
console.log(date.getHours() + "时");//获取时
console.log(date.getMinutes() + "分");//获取分
console.log(date.getSeconds() + "秒");//获取秒

日期格式化:

Date.prototype.format=function(f){

  var date={"Y":this.getFullYear(),

        "M":(this.getMonth() + 1),

        "D":this.getDate(),

        "h" : this.getHours(),

        "m" : this.getMinutes(),

        "s" : this.getSeconds()},

    d="",

    r=false,

    reg=null,

    _d="";

  for(d in date){

    reg=new RegExp("["+d+"]{1,}","g");

    r=reg.test(f);

    if(r){

      _d=date[d];

      f = f.replace(reg, _d < 10 ? ("0" + _d) : _d);}

  }

  return f;}}

获取指定日期所在月份的天数(判断闰年与平年):

function getMonthDays(Y, M){
  //Y代表年份;M 代表为月数0~11,月份加1,但是第3个参数为0,所以不+1;第3个参数要求最小为1,但是设置0,就变成M月的最后一天了
  return new Date(Y, M, 0).getDate();
}

function getYearType(Y){
  return getMonthDays(Y, 2) == 28 ? "平年" : "闰年" ;
}

倒计时:

function getCountDown(Y, M, D, h, m, s){
  Y = Y || 0;
  M = M || 0;
  D = D || 0;
  h = h || 0;
  m = m || 0;
  s = s || 0;
  var date = new Date(Y, M-1, D, h, m, s),
  //转换为时间戳,方便计算差值
  times = date.getTime() - new Date().getTime();
  //返回天数
  return Math.ceil(times / (1000 * 60 * 60 * 24));
}

posted @ 2016-01-27 14:52  inethard  阅读(150)  评论(0编辑  收藏  举报