Date

# Date

# 构造函数创建

// 1.构造函数没有参数,则返回当前日期的Date对象
var date = new Date();

// 2.构造函数的参数为日期的毫秒数,返回距离1970年1月1日经过该毫秒后对应的日期
var date = new Date(1222233);

// 3.构造函数的参数为对应的日期字符串,返回对应的日期对象,其中年,月,日是必须的,时分秒可选
//实际上,上面这种直接将表示日期的字符串传递给Date构造函数,会在后台调用Date.parse
var date = new Date('2016-01-01');
var date = new Date('2016/01/01 12:00:00');

// 4.构造函数的参数分别为年份,基于0的月份(0-11),月中的哪一天(1-31),小时数(0-23),分钟,秒以及毫秒。
// 在这些参数中,只有前两个参数(年和月)是必需的。如果没有提供月中的天数,则假设天数为1,如果省略其他参数,则统统假设为0
// 实际上,上面这种情况的构造函数,在后台调用了Date.UTC
var date = new Date(2016,4,5,17,55,55);

# 基本方法

//getYear获取的时间如果小于1900,那就要加上1900
//比如 2017 ,getYear获取的时间就是117,加上1900就是2017
var myYears = ( date.getYear() < 1900 ) ? ( 1900 + date.getYear() ) : date.getYear();

//getFullYear获取的就是当前系统本地的年
let year = date.getFullYear();

//由于js的月份是从0开始的,所以月份加上1
let month = date.getMonth()+1;

//返回的是一个月中的某一天1-31
let myDate = date.getDate();

//返回的是一个星期中的某一天0-6,0是一个星期的第一天星期天
let myDay = date.getDay();

//获取24小时格式的小时
let hours =  date.getHours();

//分
let minutes = date.getMinutes();

//秒
let seconds = date.getSeconds();

//当前时间的毫秒(0-999),获取更精确的时间
let milliseconds = date.getMilliseconds();

# 时间戳

//获取1970到现在的毫秒数
let time = date.getTime();

//以毫秒数设置日期,这常常会改变整个日期对象
date.setTime(时间戳);

//返回Date对象的原始值的毫秒数,
//返回值和方法 Date.getTime 返回的值相等。
let valueOfTime = date.valueOf();

// Date.now() 返回调用该方法的日期和时间的毫秒数
Date.now()

//parse() 方法可解析一个日期时间字符串,
//并返回 1970/1/1 午夜距离该日期时间的毫秒数。
//这个毫秒数是把当前毫秒变成000的毫秒数
let parseTime = Date.parse(date.toString());

//返回本地时间与格林威治标准时间 (GMT) 的分钟差,了解一下
let timezoneOffset = date.getTimezoneOffset();

//当前毫秒数转化为时分秒
let timeToDate = new Date(1487590667000).toLocaleString();
console.log(timeToDate);
console.log(timeToDate.split("/").join('-'));

# Date转换

//Date 对象,日期字符串
console.log(date.toDateString());

//Date 对象,时间字符串
console.log(date.toTimeString());

//Date 对象,日期+时间字符串
console.log(date.toString());

//日期字符串,根据本地时间格式
console.log(date.toLocaleDateString());

//时间字符串,根据本地时间格式
console.log(date.toLocaleTimeString());

//日期+时间字符串,根据本地时间格式
console.log(date.toLocaleString());

# 常用方法

# 时间格式化

// 对Date的扩展,将 Date 转化为指定格式的String
// 年(y) 月(M)、日(d)、小时(h)、分(m)、秒(s) 
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss") ==> 2006-07-02 08:09:04
// (new Date()).Format("yyyy-M-d h:m:s")      ==> 2006-7-2 8:9:4
function dateFormat(d,fmt = 'yyyy-MM-dd') {
	const date = d ? new Date(d) : new Date()
    const opt = {
      'y+': date.getFullYear().toString(), // 年
      'M+': (date.getMonth() + 1).toString(), // 月
      'd+': date.getDate().toString(), // 日
      'h+': date.getHours().toString(), // 时
      'm+': date.getMinutes().toString(), // 分
      's+': date.getSeconds().toString() // 秒
    }
    for (const k in opt) {
      const ret = new RegExp('(' + k + ')').exec(fmt)
      if (ret) {
        if (/(y+)/.test(k)) {
          fmt = fmt.replace(ret[1], opt[k].substring(4 - ret[1].length))
        } else {
          fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }
      }
    }
    return fmt
};
dateFormat('yyyy-MM-dd hh:mm:ss');

# 判断字符串是否是时间

if(isNaN(data)&&!isNaN(Date.parse(data))){
  console.log("data是日期格式!")
}

# 获取今年有多少周

// 获取今年有多少周
function getTotalWeek(year) {
  // 一年第一天是周几
  var first = new Date(year,0,1).getDay()
  // 计算一年有多少天
  if((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
      var allyears = 366
  }else {
      var allyears = 365
  }
  // 计算一年有多少周
  var week = parseInt((allyears + first) / 7)
  if(((allyears + first) % 7) != 0) {
      week += 1
  }
  return week
}

# 当前周

// 获取当前是一年中的第几周
function getCurrentWeek() {
  var date = new Date()
  var beginDate = new Date(date.getFullYear(), 0, 1);
  var week = Math.ceil((parseInt((date - beginDate) / (24 * 60 * 60 * 1000)) + 1 + beginDate.getDay()) / 7);
  return week;
}

# 获取星期数

// 获取当前星期几
function getWeekDate() {
  var now = new Date();
  var day = now.getDay();
  var weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
  var week = weeks[day];
  return week;
}

# 获取当月多少天

// 获取当前月份共有多少天
function getCountDays() {
    var curDate = new Date();
  /* 获取当前月份 */
    var curMonth = curDate.getMonth();
  /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
  curDate.setMonth(curMonth + 1);
  /* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
  curDate.setDate(0);
  /* 返回当月的天数 */
  return curDate.getDate();
}

# 判断闰年

// 判断闰年
Date.prototype.isLeapYear = function(){
  return (0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0)));
}

# 求两个时间的天数差

// 求两个时间的天数差 日期格式为 YYYY-MM-dd
function daysBetween(DateOne,DateTwo) {
  var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));
  var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);
  var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));
  var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('-'));
  var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('-')+1);
  var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('-'));
  var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear))/86400000);
  return Math.abs(cha);
}

# 日期计算

// 日期计算
Date.prototype.DateAdd = function(strInterval, Number) {
  //第一个参数是指在提供的时间上加的是时,分,秒,年,月,日
  //第二个参数是指加的第一个参数的个数
  var dtTmp = this;
  switch (strInterval) {
    case 's' :return new Date(Date.parse(dtTmp) + (1000 * Number));//秒
    case 'n' :return new Date(Date.parse(dtTmp) + (60000 * Number));  //分钟
    case 'h' :return new Date(Date.parse(dtTmp) + (3600000 * Number));  //小时
    case 'd' :return new Date(Date.parse(dtTmp) + (86400000 * Number));  //天
    case 'w' :return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));//周
    case 'q' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number*3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());  //季度
    case 'm' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());  //月
    case 'y' :return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());  //年
  }
}

# 获取日期数据信息

// 取得日期数据信息
// 参数 interval 表示数据类型
// y 年 m月 d日 w星期 ww周 h时 n分 s秒
Date.prototype.DatePart = function(interval){
  var myDate = this;
  var partStr='';
  var Week = ['日','一','二','三','四','五','六'];
  switch (interval){
    case 'y' :partStr = myDate.getFullYear();break;
    case 'm' :partStr = myDate.getMonth()+1;break;
    case 'd' :partStr = myDate.getDate();break;
    case 'w' :partStr = Week[myDate.getDay()];break;
    case 'ww' :partStr = myDate.WeekNumOfYear();break;
    case 'h' :partStr = myDate.getHours();break;
    case 'n' :partStr = myDate.getMinutes();break;
    case 's' :partStr = myDate.getSeconds();break;
  }
  return partStr;
}

# 日期合法性校验

// 日期合法性验证
// 格式为:YYYY-MM-DD或YYYY/MM/DD
function IsValidDate(DateStr){
    var sDate=DateStr.replace(/(^\s+|\s+$)/g,''); //去两边空格;
    if(sDate=='') return true;
    //如果格式满足YYYY-(/)MM-(/)DD或YYYY-(/)M-(/)DD或YYYY-(/)M-(/)D或YYYY-(/)MM-(/)D就替换为''
    //数据库中,合法日期可以是:YYYY-MM/DD(2003-3/21),数据库会自动转换为YYYY-MM-DD格式
    var s = sDate.replace(/[\d]{ 4,4 }[\-/]{ 1 }[\d]{ 1,2 }[\-/]{ 1 }[\d]{ 1,2 }/g,'');
    if (s=='') //说明格式满足YYYY-MM-DD或YYYY-M-DD或YYYY-M-D或YYYY-MM-D
    {
      var t=new Date(sDate.replace(/\-/g,'/'));
      var ar = sDate.split(/[-/:]/);
      if(ar[0] != t.getYear() || ar[1] != t.getMonth()+1 || ar[2] != t.getDate())
      {
        //alert('错误的日期格式!格式为:YYYY-MM-DD或YYYY/MM/DD。注意闰年。');
        return false;
      }
    }
    else
    {
      //alert('错误的日期格式!格式为:YYYY-MM-DD或YYYY/MM/DD。注意闰年。');
      return false;
    }
    return true;
}

# 比较时间差

// 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串(Fri Sep 11 2015 10:23:59 GMT+0800)
Date.prototype.DateDiff = function(strInterval, dtEnd) {
  var dtStart = this;
  if (typeof dtEnd == 'string' )//如果是字符串转换为日期型
  {
    dtEnd = StringToDate(dtEnd);
  }
  switch (strInterval) {
    case 's' :return parseInt((dtEnd - dtStart) / 1000);  //秒
    case 'n' :return parseInt((dtEnd - dtStart) / 60000);  //分钟
    case 'h' :return parseInt((dtEnd - dtStart) / 3600000);  //小时
    case 'd' :return parseInt((dtEnd - dtStart) / 86400000);  //天
    case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7)); //周
    case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);  //月
    case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();  //年
  }
}