首页 > 技术文章 > javascript时间函数封装

yangguanglei 2020-11-02 19:32 原文

javascript时间函数封装

 * 判断时候是1-9,是的话就在前面添加0,变成01-09
 * @param n 字符串
 */
export const formatNumber = function(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

/**
 * 时间戳和日期时间转换(年月日+时间)
 * 时间格式:YYYY-MM-DD hh:mm:ss
 * @param times
 */
export const formatDateTime = function(times) {
  var now = new Date(times);
  var year = now.getFullYear();
  //注意月份需要加1,返回值0-11
  var month = now.getMonth() + 1;
  var date = now.getDate();
  var hour = now.getHours();
  var minute = now.getMinutes();
  var second = now.getSeconds();
  return year + '-' + formatNumber(month) + '-' + formatNumber(date) + ' ' + formatNumber(hour) + ':' + formatNumber(minute) + ':' + formatNumber(second);
};

/**
 * 时间戳和日期转换(年月日)
 * 格式:YYYY-MM-DD
 * @param {*} times
 */
export const formatDate = function(times) {
  var now = new Date(times);
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var date = now.getDate();
  return year + '-' + formatNumber(month) + '-' + formatNumber(date);
};

/**
 * 时间戳转为 年月格式
 * 格式:YYYY-MM
 * @param {*} times
 */
export const formatYear = function(times) {
  var now = new Date(times);
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  return year + '-' + formatNumber(month);
};

/**
 * 时间戳转为 月日格式
 * 格式:MM-DD
 * @param {*} times
 */
export const formatMonth = function(times) {
  var now = new Date(times);
  var month = now.getMonth() + 1;
  var date = now.getDate();
  return formatNumber(month) + '-' + formatNumber(date);
};

/**
 * 获取一个月的第一天
 * @param {标准时间} times
 */
export const getCurrentMonthFirst = function(times) {
  var now = new Date(times);
  now.setDate(1);
  var month = parseInt(now.getMonth() + 1);
  var date = now.getDate();
  return now.getFullYear() + '-' + formatNumber(month) + '-' + formatNumber(date);
};

/**
 * 获取一个月的最后一天
 * @param {标准时间} times
 */
export const getCurrentMonthLast = function(times) {
  var now = new Date(times);
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var endOfMonth = new Date(year, month, 0).getDate();
  return now.getFullYear() + '-' + formatNumber(month) + '-' + endOfMonth;
};

/**
 *  获取当月的天数
 */
export const mGetDate = function() {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  //获取本月的第0天就是上月的最后一天
  const days = new Date(year, month, 0);
  return days.getDate();
};
/**
 * 获取本周所有日期
 */
export const getWeekDay = function() {
  const date = new Date();
  const Monday = formatMonth(date.setDate(date.getDate() - date.getDay() + 1));
  const Tuesday = formatMonth(date.setDate(date.getDate() - date.getDay() + 2));
  const Wednesday = formatMonth(date.setDate(date.getDate() - date.getDay() + 3));
  const Thursday = formatMonth(date.setDate(date.getDate() - date.getDay() + 4));
  const Friday = formatMonth(date.setDate(date.getDate() - date.getDay() + 5));
  const Saturday = formatMonth(date.setDate(date.getDate() - date.getDay() + 6));
  const Sunday = formatMonth(date.setDate(date.getDate() - date.getDay() + 7));
  const weekDay = [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday];
  return weekDay;
};
/**
 * 获取当月所有日期
 */
export const getNowM = function() {
  let now = new Date();
  let current_month_num = mGetDate();
  let current_month = [];
  for (let i = 1; i <= current_month_num; i++) {
    let day = now.setDate(i);
    let everyDay = formatMonth(day);
    current_month.push(everyDay);
  }
  return current_month;
};

/**
 * 计算时间差
 * @param {Data} startTime 开始时间
 * @param {Data} endTime   结束时间
 * return xx年xx天  || xx天xx小时 || xx小时xx分
 */
export const getDateDiff = function(startTime, endTime) {
  var sTime = new Date(startTime); //开始时间
  var eTime = new Date(endTime); //结束时间
  var timeOff = eTime - sTime; //相差时间戳(毫秒数)
  var timeMinute = 1000 * 60;
  var timeHour = 1000 * 3600;
  var timeDay = 1000 * 3600 * 24;
  var timeYear = 1000 * 3600 * 24 * 365;
  if (timeOff / timeYear >= 1) {
    return parseInt(timeOff / timeYear) + '年' + parseInt((timeOff % timeYear) / timeDay) + '天';
  } else if (timeOff / timeDay >= 1) {
    return parseInt(timeOff / timeDay) + '天' + parseInt((timeOff % timeDay) / timeHour) + '小时';
  } else {
    return parseInt(timeOff / timeHour) + '小时' + parseInt((timeOff % timeHour) / timeMinute) + '分';
  }
};

/**
 * 按照用户需要格式化时间
 * @param {Data} times 标准时间
 * @param {String} rule 格式化规则
 */
export const FormatDate = function(date, format) {
  if (!date || date === '') {
    return '';
  }
  if (!format || format === '') {
    return formatDateTime(date);
  }

  if (typeof date === 'string') {
    var mts = date.match(/(\/Date\((\d+)\)\/)/);
    if (mts && mts.length >= 3) {
      date = parseInt(mts[2]);
    }
  }

  date = new Date(date);
  if (!date || date.toUTCString() === 'Invalid Date') {
    return '';
  }

  var map = {
    M: date.getMonth() + 1, // 月份
    d: date.getDate(), // 日
    h: date.getHours(), // 小时
    m: date.getMinutes(), // 分
    s: date.getSeconds(), // 秒
    q: Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };

  format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
    var v = map[t];
    if (v !== undefined) {
      if (all.length > 1) {
        v = '0' + v;
        v = v.substr(v.length - 2);
      }
      return v;
    } else if (t === 'y') {
      return (date.getFullYear() + '').substr(4 - all.length);
    }
    return all;
  });
  return format;
};

推荐阅读