js 相关日期的函数

10 篇文章 0 订阅

近期项目里面需要处理一些时间日期的数据,所以封装了些函数(如下)

获取年月日

//获取年月日
export function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

获取年月日(d天前或者d周)

//获取年月日  (d天前或d周)
export function getYesFormatDate(d, type) {
  var weekDay = new Date().getDay();
  if (weekDay == 0) {
    //如果是周日,则设为7天
    weekDay = 7;
  }
  //weekDay-当前是周几
  var time;
  if (type == 'day') {
    time = (new Date).getTime() - 24 * 60 * 60 * 1000 * d
  } else if (type == 'week') {
    time = (new Date).getTime() - 24 * (d * 7 - 1 + weekDay) * 60 * 60 * 1000;
  } else {
    time = (new Date).getTime();
  }
  var date = new Date(time);  //获取日期
  var seperator1 = "-";
  var year = type == 'year' ? date.getFullYear() - d : date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var yesday = year + seperator1 + month + seperator1 + strDate;
  return yesday;
}

获取上月年月

//获取上月年月
export function getMoutnFormatDate() {
  var time = (new Date).getTime();
  var date = new Date(time);  //获取的是今天的日期
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (month == 0) {
    month = "12";
    year = year - 1;
  }
  var yesMouth = year + seperator1 + month;
  return yesMouth;
}

获取六月前年月

//获取6月前 年月
export function getSixMoutnFormatDate() {
  var time = (new Date).getTime();
  var date = new Date(time);  //获取的是今天的日期
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() - 6;
  if (month < 0) {
    year = year - 1;
    let newMonth = month + 13;
    if (newMonth <= 9) {
      month = "0" + newMonth;
    } else {
      month = newMonth;
    }
  } else if (month >= 0) {
    let newMonth = month + 1;
    month = "0" + newMonth
  }
  var sixMouth = year + seperator1 + month;
  return sixMouth;
}

获取当前年

//获取当前年
export function getYearFormatDate() {
  var time = (new Date).getTime();
  var date = new Date(time);
  var year = date.getFullYear() - 1;
  return year;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值